Algorithm:Leetcode 19. Remove Nth Node From End of List
給定一個鏈表,刪除鏈表的倒數第 n 個節點,並且返回鏈表的頭結點。
示例:
給定一個鏈表: 1->2->3->4->5, 和 n = 2.
當刪除了倒數第二個節點後,鏈表變爲 1->2->3->5.
說明:
給定的 n 保證是有效的。
進階:
你能嘗試使用一趟掃描實現嗎?
解法一:雙指針
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
if(n <=0)
return head;
ListNode dummyHead = new ListNode(-1);
dummyHead.next = head;
ListNode p = dummyHead;
ListNode q = dummyHead;
int i=0;
for(; i<n && p!=null; i++) {
p = p.next;
}
if(i < n) {
// n is larger than list.size
return head;
}
// move to the end
while(p.next != null) {
p = p.next;
q = q.next;
}
// q.next is the nth from the end
q.next = q.next.next;
return dummyHead.next;
}
}
解法二:先遍歷一次計算鏈表長度,從而計算出倒數第n個元素是整數第幾個
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
int size=0;
ListNode p = head;
while(p != null) {
p = p.next;
size++;
}
if(n <=0 || n > size)
return head;
ListNode dummyHead = new ListNode(-1);
dummyHead.next = head;
p = dummyHead;
int m = size - n;
while(m > 0) {
p = p.next;
m--;
}
p.next = p.next.next;
return dummyHead.next;
}
}
Review:
Tip:
Share: