题目描述:Given a linked list, remove the n-th node from the end of list
and return its head. Note:Given n will always be valid.
Follow up:
Could you do this in one pass?
解题思路:创建两个和原列表相同的列表l1和l2,他们的头结点分别为p1和p2,开始前,p2先向前移n步,此时若p2为空,说明倒数第N个结点就是头结点,故返回head.next,若p2不为空,则p1和p2同时前移至p2.next为空,此时p1.next就是需要删除的结点。
代码如下:
/**
* 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) {
ListNode p1 = head;
ListNode p2 = head;
for(int i = 0;i<n;i++){
p2=p2.next;
}
if(p2==null) return head.next;
while(p2.next!=null){
p1=p1.next;
p2=p2.next;
}
p1.next=p1.next.next;
return head;
}
}