【剑指offer 面试题15】链表中倒数第K个结点
思路:
定义两个指针同时指向head,第一个指针先走K-1步,随后二个指针同时移动,当第一个指针到末尾处时,第二个指针所指向的即为倒数第K个结点。
1 #include <iostream> 2 using namespace std; 3 4 struct ListNode 5 { 6 int val; 7 ListNode *next; 8 ListNode(int v = 0):val(v), next(NULL){} 9 }; 10 11 ListNode *findLastKthnumber(ListNode **pListHead, unsigned int k) 12 { 13 if(*pListHead == NULL || k == 0) 14 return NULL; 15 16 ListNode *pFirst = *pListHead; 17 ListNode *pSecond = *pListHead; 18 19 for(int i = 0; i < k - 1; i++) 20 { 21 pFirst = pFirst->next; 22 if(pFirst == NULL) 23 return NULL; 24 } 25 26 while(pFirst->next != NULL) 27 { 28 pFirst = pFirst->next; 29 pSecond = pSecond->next; 30 } 31 32 return pSecond; 33 } 34 35 int main() 36 { 37 ListNode *first = new ListNode(1); 38 ListNode *head = first; 39 40 ListNode *second = new ListNode(2); 41 first->next = second; 42 first = first->next; 43 44 ListNode *third = new ListNode(3); 45 first->next = third; 46 first = first->next; 47 48 cout<<"初始链表: "; 49 ListNode *print = head; 50 while(print != NULL) 51 { 52 cout<<print->val<<" "; 53 print = print->next; 54 } 55 cout<<endl<<endl; 56 57 cout<<"倒数第零个结点: "; 58 ListNode *res = findLastKthnumber(&head, 0); 59 if(res != NULL) 60 cout<<res->val<<endl; 61 else 62 cerr<<"error!"<<endl; 63 64 cout<<"倒数第一个结点: "; 65 res = findLastKthnumber(&head, 1); 66 if(res != NULL) 67 cout<<res->val<<endl; 68 else 69 cerr<<"error!"<<endl; 70 71 cout<<"倒数第二个结点: "; 72 res = findLastKthnumber(&head, 2); 73 if(res != NULL) 74 cout<<res->val<<endl; 75 else 76 cerr<<"error!"<<endl; 77 78 cout<<"倒数第三个结点: "; 79 res = findLastKthnumber(&head, 3); 80 if(res != NULL) 81 cout<<res->val<<endl; 82 else 83 cerr<<"error!"<<endl; 84 85 cout<<"倒数第四个结点: "; 86 res = findLastKthnumber(&head, 4); 87 if(res != NULL) 88 cout<<res->val<<endl; 89 else 90 cerr<<"error!"<<endl; 91 }
测试结果:
初始链表: 1 2 3 倒数第零个结点: error! 倒数第一个结点: 3 倒数第二个结点: 2 倒数第三个结点: 1 倒数第四个结点: error!