鍊錶中倒數第K個結點

2021-07-11 21:03:01 字數 989 閱讀 5950

//輸入乙個鍊錶,輸出該鍊錶中倒數第k個結點。(k=1,2...)

//如:鍊錶1、2、3、4、5、6.倒數第3個節點為4。

#include "iostream"

using namespace std;

struct listnode

};//遍歷兩次

listnode* findkthtotail0(listnode *plisthead, unsigned int k)

if (k > len)

else

return p; }}

//遍歷1次,雙指標

listnode* findkthtotail1(listnode *plisthead, unsigned int k)

if (pahead == null)

return null;

listnode* kthtotail = plisthead;

while (pahead->m_pnext != null)

return kthtotail;

}listnode* createlist(int* a, int n)

return head;

}void destory(listnode* head)

}void listprint(listnode* head)

cout << endl;

}void test()

; listnode* head = createlist(a, sizeof(a) / sizeof(int));

listprint(head);

listnode* p = findkthtotail1(head, 4);

if (p != null)

destory(head);

}int main()

注意**的魯棒性,輸入為空,k=0,或k值大於list.length()的情況。

鍊錶中倒數第k個結點

題目描述 輸入乙個鍊錶,輸出該鍊錶中倒數第k個結點。輸入 輸入可能包含多個測試樣例,輸入以eof結束。對於每個測試案例,輸入的第一行為兩個整數n和k 0 n k 1000 n代表將要輸入的鍊錶元素的個數,k代表要查詢倒數第幾個的元素。輸入的第二行包括n個數t 1 t 1000000 代表鍊錶中的元素...

鍊錶中倒數第k個結點

題目 輸入乙個鍊錶,輸出該鍊錶中倒數第k個結點。分析 對於此題,考慮單鏈表實現,單鏈表只能從頭到尾遍歷,而要找到倒數第k個結點,就需要確定,正數是第幾個結點,假設結點總數為n,最後乙個結點位置為n 1,而倒數第k個結點的位置就為n k 1,如果從頭節點開始遍歷,只要遍歷到n k 1步就可以,這就意味...

鍊錶中倒數第k個結點

題目描述 輸入乙個鍊錶,輸出該鍊錶中倒數第k個結點。思路一 設定兩個指標pre和last,先讓pre移動k 1步,如果此時pre為空,則k 鍊錶長度,返回null,否則讓pre和last同時移動。步驟為 pre pre.next if pre null 若為真,進入 否則進入 last last.n...