题目描述
输入一个链表,输出该链表中倒数第k个结点。
基本思想:定义两个指针a,b分别指向头节点, a指针先向前走k-1步(注意:因为倒数节点是从倒数第一个结点开始的,而不是零),然后a指针和b指针一起向前移动,
直到a->next == NULL。此时,b指针所指向的结点。即为倒数第K个结点。
边界条件:1.输入的pListHead为空指针的情况;
2.输入的以pListHead为头结点的链表的节点总数少于K的情况;
3.输入K为0的情况。
#include <iostream> #include <algorithm> #include "string.h" #include "stdio.h" #include <vector> #include <deque> #include<stack> using namespace std; struct ListNode { int val; struct ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; class List{ public: ListNode* CreatList(int* arr,int len) { int val; ListNode* pHead = new ListNode(arr[0]); ListNode* pCurrent=NULL; ListNode* rear = pHead; int count = 1; while(count<len) { ListNode* pCurrent = new ListNode(arr[count]); rear->next = pCurrent; rear = pCurrent; count++; } rear->next = NULL; return pHead; } void ShowList(ListNode* pHead) { while(pHead) { cout<<pHead->val<<" "; pHead = pHead->next; } cout<<endl; } ListNode* GetLastNode(ListNode* pHead) { ListNode* pNode = pHead; while(pNode->next!=NULL) { pNode=pNode->next; } return pNode; } }; class Sort{ public: ListNode* FindKthToTail(ListNode* pListHead, unsigned int k) { if(pListHead == NULL||k==0) return NULL; ListNode* pNode = pListHead; ListNode* p = pListHead; int count = 0; pNode=pListHead; for(int i=0;i<k-1;i++) { if(pNode->next!=NULL) pNode = pNode->next; else return NULL; } while(pNode->next!=NULL) { p = p->next; pNode=pNode->next; } return p; } }; int main() { int array[]={3,4,5,1,2,8,7}; List list; Sort sort; ListNode* pHead = list.CreatList(array,sizeof(array)/sizeof(array[0])); list.ShowList(pHead); ListNode* pNode = sort.FindKthToTail(pHead,7); cout<<pNode->val<<endl; return 0; }
时间: 2024-12-23 15:23:54