【LeetCode】19. Remove Nth Node From End of List - Java實現
阿新 • • 發佈:2018-11-24
文章目錄
1. 題目描述:
Given a linked list, remove the n-th node from the end of list and return its head.
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.
Follow up:
Could you do this in one pass?
2. 思路分析:
題目的意思是給定一個連結串列,刪除倒數第n個節點。
要刪除倒數第n個節點,則需要定位到倒數第n+1個節點,然後將其next指向倒數第n-1個節點即可。
此題用到了2個指標,先將指標p指向第n+1個節點,然後將指標q指向第1個節點,2個指標同時向後遍歷連結串列,則當p指向最後一個節點時,q則一定指向倒數第n+1個節點,然後將q的next節點刪除即可。
3. Java程式碼:
原始碼
程式碼:
public static ListNode removeNthFromEnd(ListNode head, int n) {
ListNode p = head;
for (int i = 0; i < n; i++) {
p = p.next;
}
// 表示刪除的是第一個節點
if (p == null) {
return head.next;
}
ListNode q = head;
while (p.next != null) {
p = p.next;
q = q.next;
}
// q正好指向待刪除節點的前一個節點
q.next = q.next.next;
return head;
}