Created
April 1, 2018 03:06
-
-
Save Lemon-XQ/5aa76f9a465c5155461cfad20bf60163 to your computer and use it in GitHub Desktop.
[单链表找倒数第k个数] #数据结构
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
typedef struct ListNode{ | |
int data; | |
struct ListNode* next; | |
}ListNode; | |
ListNode* findKthToTail(ListNode* pHead,int k){ | |
ListNode* pFast=pHead,pSlow=pHead; | |
if(pHead == null || k<=0 || k> ListLength(pHead)) | |
return null; | |
if(pHead->next == null) | |
return pHead; | |
for(int i=0;i<k-1;i++){ | |
pFast = pFast->next; | |
} | |
while(pFast->next != null){ | |
pFast = pFast->next; | |
pSlow = pSlow->next; | |
} | |
return pSlow; | |
} | |
int ListLength(ListNode* pHead){ | |
int len = 1; | |
while(pHead->next){ | |
len++; | |
pHead = pHead->next; | |
} | |
return len; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment