華為OJ:輸出單向連結串列中倒數第k個結點
阿新 • • 發佈:2019-02-12
輸入一個單向連結串列,輸出該連結串列中倒數第k個結點,連結串列的倒數第0個結點為連結串列的尾指標。
連結串列結點定義如下:
struct ListNode
{
int m_nKey;
ListNode* m_pNext;
};
詳細描述:
介面說明
原型:
ListNode* FindKthToTail(ListNode* pListHead, unsignedint k);
輸入引數:
ListNode* pListHead 單向連結串列
unsigned int k 倒數第k個結點
輸出引數(指標指向的記憶體區域保證有效):
無
返回值:
正常返回倒數第k個結點指標,異常返回空指標
#include <iostream> using namespace std; typedef struct node { int nodevalue; struct node *next; }node, linklist; //為了得到倒數第k個結點,很自然的想法是先走到連結串列的尾端,再從尾端回溯k步。 //可是輸入的是單向連結串列,只有從前往後的指標而沒有從後往前的指標。 //在遍歷時維持兩個指標,第一個指標從連結串列的頭指標開始遍歷,在第k-1步之前,第二個指標保持不動;在第k-1步開始, //第二個指標也開始從連結串列的頭指標開始遍歷。由於兩個指標的距離保持在k-1, //當第一個(走在前面的)指標到達連結串列的尾結點時,第二個指標(走在後面的)指標正好是倒數第k個結點。 linklist *BuildList( int m) { node *head = (node*)malloc(sizeof(node)); head->next = NULL; head->nodevalue=m;//第一個存放結點個數 linklist *t = head; if (head) { for (int i = 0; i < m ; i++) { node *nextnode = (node *)malloc(sizeof(node)); nextnode->next = NULL;//新建節點 cin >> nextnode->nodevalue;// head->next = nextnode; head = nextnode; } } else { cout << "head new comes error!" << endl; } return t; } linklist* FindKthToTail_Solution2(linklist *pListHead, unsigned int k) { if (pListHead == NULL) return NULL; linklist *pAhead = pListHead; linklist *pBehind = NULL; for (unsigned int i = 0; i < k; i++) { if (pAhead->next != NULL)//尼瑪,要從倒數第0個開始算起!!!! pAhead = pAhead->next; else { // if the number of nodes in the list is less than k, // do nothing return NULL; } } pBehind = pListHead; // the distance between pAhead and pBehind is k // when pAhead arrives at the tail, p // Behind is at the kth node from the tail while (pAhead->next!= NULL) { pAhead = pAhead->next; pBehind = pBehind->next; } return pBehind; } int main() { int nodenum; cin >> nodenum; linklist *p; p = BuildList(nodenum); int k; cin >> k; linklist *resu = FindKthToTail_Solution2(p->next,k); cout << resu->nodevalue << endl; return 1; }