移除連結串列倒數第N個節點
阿新 • • 發佈:2018-12-20
給定一個連結串列,刪除連結串列的倒數第 n 個節點,並且返回連結串列的頭結點。
示例:
給定一個連結串列: 1->2->3->4->5, 和 n = 2. 當刪除了倒數第二個節點後,連結串列變為 1->2->3->5.
思路:雙指標法
需要用兩個指標來幫助我們解題,pre和cur指標。首先cur指標先向前走N步,如果此時cur指向空,說明N為連結串列的長度,則需要移除的為首元素,那麼此時我們返回head->next即可,如果cur存在,我們再繼續往下走,此時pre指標也跟著走,直到cur為最後一個元素時停止,此時pre指向要移除元素的前一個元素,我們再修改指標跳過需要移除的元素即可。
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public ListNode removeNthFromEnd(ListNode head, int n) { ListNode pre = head; ListNode cur = head; for(int i = 0;i < n && cur != null; i++){//找到第n個結點 cur = cur.next; } if(cur == null){ return head.next; } // cur與pre相差n-1個結點 // 當cur.next為null,pre在倒數第n+1個位置 while(cur.next != null){ cur = cur.next; pre = pre.next; } pre.next = pre.next.next; return head; }