Given a linked list, remove the nth node from the end of list and return its head.
Example:
1
2
3
Given linked list: 1->2->3->4->5, and n = 2.
After removing the second node from the end, the linked list becomes 1->2->3->5.
提示
解題應用
LinkedList
Pointer
Note:
Given n will always be valid. Try to do this in one pass.
Default:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
funcremoveNthFromEnd(head *ListNode, n int) *ListNode {
}
解答思路:
非常典型的LinkedList題目,如果以前有碰過指標的話,那麼一定會接觸到這類題型,而這邊要你移除倒數第n個的節點,以 A B C D E 為例,如果給的 n=2 那我們要移除D的點,可惜此LinkedList僅是由頭往下做銜接,所以沒有辦法從尾走回頭,倒不如去想由頭來算是第幾個,以上述來說 5(總數)-2(從尾算)+1=4(從頭算) 不過我們一開始並不知道總數是多數,所以這邊我先遍歷一次整個List之後才真正去移除我們想要的節點。