[剑指offer][面试题15]输出链表倒数第K个结点

来源:互联网 发布:下载wps办公软件mac版 编辑:程序博客网 时间:2024/05/16 17:32

输入一个单向链表,输出该链表中倒数第k个结点。只能遍历链表一次。最后一个结点认为是倒数第一个结点。

#include <iostream>using namespace std;struct Node{    int   m_Data;    Node *m_pNext;    }; Node* findKthNodeToTail(Node *pHead, int iK){if (pHead==NULL || iK<=0){return NULL;}Node *pNode0 = pHead;Node *pNode1 = pHead;while (pNode1 && --iK){pNode1 = pNode1->m_pNext;}if (pNode1==NULL){return NULL;}else{while (pNode1->m_pNext){pNode0 = pNode0->m_pNext;pNode1 = pNode1->m_pNext;}return pNode0;}}void printList(Node *pHead)  {  bool bEmpty = true;  while (pHead){  bEmpty = false;  cout<<pHead->m_Data<<"->";    pHead = pHead->m_pNext;  }  if (!bEmpty){  cout<<"NULL"<<endl;    }  } int main(){Node nodeA5 = {1, NULL};    Node nodeA4 = {2, &nodeA5};    Node nodeA3 = {3, &nodeA4};    Node nodeA2 = {4, &nodeA3};    Node nodeA1 = {5, &nodeA2};    Node nodeA0 = {6, &nodeA1};    Node *pHeadA = &nodeA0;    cout<<"Linked List: "<<endl;    printList(pHeadA);  for (int i=-1; i<8; i++){cout<<"Try to find "<<i<<"-th element in reverse order: "<<endl;Node *pNode = findKthNodeToTail(pHeadA, i);  if (pNode){cout<<"found: "<<pNode->m_Data<<endl;}else{cout<<"Not found!"<<endl;}}}