查找链表倒数第k个数
题目:输入一个单向链表,输出该链表中倒数第k个结点。链表的倒数第0个结点为链表的尾指针。
链表结点定义如下:
struct ListNode { int m_nKey; ListNode* m_pNext; };
答:
#include "stdafx.h" #include <iostream> #include <fstream> using namespace std; struct ListNode { int m_nKey; ListNode* m_pNext; }; //构造链表 void CreateList(ListNode *&pHead) { fstream fin("list.txt"); ListNode *pNode = NULL; ListNode *pTmp = NULL; int data; fin>>data; while (data) { pNode = new ListNode; pNode->m_nKey = data; pNode->m_pNext = NULL; if (NULL == pHead) { pHead = pNode; pTmp = pNode; } else { pTmp->m_pNext = pNode; pTmp = pNode; } fin>>data; } } int _tmain(int argc, _TCHAR* argv[]) { ListNode *pHead = NULL; CreateList(pHead); ListNode *p = pHead; ListNode *q = pHead; int k = 5; for (int i = 0 ; NULL != p && i < k; i++) { p = p->m_pNext; } if (NULL == p) { return; } while (NULL != p) { p = p->m_pNext; q = q->m_pNext; } cout<<q->m_nKey<<endl; cout<<endl; return 0; }
运行界面如下:
建造链表的list.txt文件如下:
12 11 10 9 8 7 6 5 4 3 2 1 0