Skip to content

Instantly share code, notes, and snippets.

@Lemon-XQ
Created April 1, 2018 03:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Lemon-XQ/5aa76f9a465c5155461cfad20bf60163 to your computer and use it in GitHub Desktop.
Save Lemon-XQ/5aa76f9a465c5155461cfad20bf60163 to your computer and use it in GitHub Desktop.
[单链表找倒数第k个数] #数据结构
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