Microsoft100——002.链表中倒数第K个节点

来源:互联网 发布:阿特金斯减肥法 知乎 编辑:程序博客网 时间:2024/04/28 22:46
#include<iostream>using namespace std;struct ListNode{int value;ListNode *next;};ListNode* AddToTail(ListNode *pHead,int value){ListNode *pNew = new ListNode;pNew->value = value;pNew->next = NULL;if (pHead == NULL){pHead = pNew;}else{ListNode *pNode = pHead;while(pNode->next != NULL){pNode = pNode->next;}pNode->next = pNew;}return pHead;}ListNode *FindKthToTail(ListNode *pHead,int k){if(pHead==NULL || k<=0)return NULL;ListNode *pFirst=pHead;ListNode *pSecond=pHead;for (int i=0 ; i<k ; ++i){if (pFirst->next ==NULL)return NULL;pFirst = pFirst->next;}while(pFirst->next != NULL){pFirst = pFirst->next;pSecond = pSecond ->next;}return pSecond;}void main(){ListNode *phead=NULL;ListNode *temp;for (int i=0 ; i<10 ; ++i){phead = AddToTail(phead,i+1);}temp = phead;while(temp->next !=NULL){cout<<temp->value<<endl;temp = temp->next;}cout<<FindKthToTail(phead,2)->value<<endl;}

0 0
原创粉丝点击