题解 | #删除链表的倒数第n个节点#
删除链表的倒数第n个节点
http://www.nowcoder.com/practice/f95dcdafbde44b22a6d741baf71653f6
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* }
*/
public class Solution {
/**
*
* @param head ListNode类
* @param n int整型
* @return ListNode类
*/
public ListNode removeNthFromEnd (ListNode head, int n) {
// write code here
ListNode pre = new ListNode(0);
pre.next = head;
ListNode p1 = pre;
ListNode p2 = pre;
int i =0;
while(i<n){
p2=p2.next;
i++;
}
while(p2.next!=null){
p1 = p1.next;
p2 = p2.next;
}
p1.next = p1.next.next;
return pre.next;
}
}
/*
* public class ListNode {
* int val;
* ListNode next = null;
* }
*/
public class Solution {
/**
*
* @param head ListNode类
* @param n int整型
* @return ListNode类
*/
public ListNode removeNthFromEnd (ListNode head, int n) {
// write code here
ListNode pre = new ListNode(0);
pre.next = head;
ListNode p1 = pre;
ListNode p2 = pre;
int i =0;
while(i<n){
p2=p2.next;
i++;
}
while(p2.next!=null){
p1 = p1.next;
p2 = p2.next;
}
p1.next = p1.next.next;
return pre.next;
}
}