Leetcode 返回單鏈表的倒數第k個節點

2021-10-19 08:37:54 字數 652 閱讀 1055

題目描述:

輸入乙個鍊錶,輸出該鍊錶中倒數第k個結點。
測試用例:

輸入:1,

輸出:

思路:

-判斷引數的合法性;

-定義fast和slow節點分別指向頭結點;

-當fast.next != null,fast先走k-1步;

-當fast.next != null,fast和slow一起走,最終返回slow;

**如下:

class

listnode

}public

class

solution

listnode fast = head;

listnode slow = head;

for(

int i =

0; i < k-

1; i++

)else

}while

(fast.next != null)

return slow;

}}

C 返回單鏈表的第k個結點

返回單鏈表的第k個結點,雙指標可以很好地解決這個問題 listnode findkthtotail listnode plisthead,unsigned k pbehind plisthead while pahead next null return pbehind 但是這段 沒有檢查輸入合法性...

返回單鏈表的倒數第n個節點

struct list node struct list node next void data struct list node get last nth node struct list node head,unsigned int pos struct list node ret head u...

返回單鏈表的倒數第n個節點

struct list node 這個函式的名字起得不是特別的好。功能就是返回單鏈表倒數第n個節點。引數說明 struct list node head 單鏈表頭指標 unsigned int pos 倒數的個數 struct list node get last nth node struct l...