Given a linked list, remove the nth node from the end of list and return its head.
For example,
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.
Note:Given n will always be valid.
Try to do this in one pass.
大致意思就是給定一個鏈表,刪除鏈表中倒數第n個節點,只允許我們遍歷鏈表一次。
本科學習數據結構時老師留過類似的作業題,此題與其的區別是要刪除倒數第n個節點而不是查找,所以我們要查找到倒數第n+1個節點,令p和q間的距離為n+1,同時由于本題需要自己手動附加頭節點,所以初始時可以令p指向附加頭節點,q指向正數第n個節點,同時平移指針p和指針q,當指針q指向鏈表最后一個節點時,指針p恰好指向鏈表倒數第n+1個節點,即倒數第n個節點的前驅節點。該算法的時間復雜度為O(n),且只需遍歷鏈表一次;空間復雜度為O(1).
代碼如下:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode first = new ListNode(0); // 附加頭結點
first.next = head;
ListNode p = first;
ListNode q = first.next;
for(int i = 1; i < n; i++) // 將q從第1個節點移動到第n個結點
q = q.next;
while(q.next != null)
{
p = p.next;
q = q.next;
}
p.next = p.next.next;
return first.next;
}
}