原题链接在这里:https://leetcode.com/problems/remove-nth-node-from-end-of-list/
Method 1: 算出总长度,再减去n,即为要从头多动的点。但要新要求,only one pass。
Method 2: 两个指针,一个runner,一个walker,runner先走n步,随后runner和walker一起走,直到runner指为空。
Note: 1. 都是找到要去掉点的前一个点记为mark,再通过mark.next = mark.next.next去掉对应应去掉的点。
2. 注意去掉list头点的情况,e.g. 1->2, n = 2.
AC Java:
/**
* 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) {
/*Method 1
if(head == null)
return head;
int len = 0;
ListNode temp = head;
while(temp != null){
temp = temp.next;
len++;
}
if(len < n){
return head;
}
int moveNum = len - n;
ListNode dunmy = new ListNode(0);
dunmy.next = head;
temp = dunmy;
while(moveNum > 0){
temp = temp.next;
moveNum--;
}
temp.next = temp.next.next;
return dunmy.next;
*/
//Method 2
if(head == null || n == 0)
return head;
ListNode dunmy = new ListNode(0);
dunmy.next = head;
ListNode runner = dunmy.next;
ListNode walker = dunmy;
while(n>0 && runner != null){
runner = runner.next;
n--;
}
while(runner != null){
runner = runner.next;
walker = walker.next;
}
walker.next = walker.next.next;
return dunmy.next;
}
}