# 数据结构与算法 | Leetcode 19. Remove Nth Node From End of List

XAMPP教程 767浏览

/**
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {

public ListNode removeNthFromEnd(ListNode head, int n) {
return null;
}
int len = 0;
for(ListNode curr = head ; curr != null;){
len++;
curr = curr.next;
}

if(len == 0){
return null;
}

if(len == n){
}

ListNode prev = null;
int i = 0;
for(ListNode curr = head; curr != null;){
i++;
prev = curr;
curr = curr.next;

if(i == (len – n)){
prev.next = curr.next;
}
}
}
}
Leetcode测试的运行时间为6ms，超过了98.75%的java代码。

/**
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {

public ListNode removeNthFromEnd(ListNode head, int n) {
return null;
}
for(int i = 0; i < n; i++){
fast = fast.next;
}

if(fast == null){
return slow.next;
}

ListNode prev = null;
for(ListNode curr = slow; curr != null; ){
// when fast arrived at tail, remove slow.
if(fast == null){
prev.next = curr.next;
break;
}
prev = curr;
curr = curr.next;
// move fast forward
fast = fast.next;
}