Given a linked list, remove the nth node from the end of list and return its head.
For example,
Given linked list: 1->2->3->4->5, and n = 2. After removing the second node from the end, the linked list becomes 1->2->3->5.
Note:
Given n will always be valid.
Try to do this in one pass.
按照双指针的思想去考虑这个问题。比如给出了一个链表 1 2 3 4 5 , 如果想要去除导数第二个元素,让两个指针都指向头 ,先让一个指针走两步到达3,然后两个指针一起向右移动,当右指针的next为空值时,删除左指针的next 即可。上面的例子中,左指针指向3,右指针指向5。此时,先暂时保留左指针的next.next的位置,然后赋值给左指针.next , 将元素4删去。 提交的时候会出现一个元素的情况,还有空元素的情况,都需要考虑到。
代码:
package leetcode;
public class RemoveN {
public static void main(String[] args) {
RemoveN r = new RemoveN();
// TODO Auto-generated method stub
ListNode head = new ListNode(1);
ListNode cur = head;
for(int i = 1; i < 5; i++)
{
ListNode tmp = new ListNode(i+1);
cur.next = tmp;
cur = tmp;
}
ListNode n1 = new ListNode(1);
ListNode n2 = new ListNode(2);
n1.next = n2;
cur = r.removeNthFromEnd(n1,2);
for(;cur != null;)
{
System.out.println(cur.val);
cur = cur.next;
}
}
public ListNode removeNthFromEnd(ListNode head, int n) {
if(head == null )
return head;
if(head.next ==null){
return null;
}
//双指针思想
ListNode p1 = head;
ListNode p2 = head;
for(int i=0;i<n;i++){
if(p2==null){
//说明给的n大了,
return null;
}
p2 = p2.next;
}
if (p2 == null){
//删除头结点
head = head.next;
return head;
}else{
while(p2.next != null){
p1= p1.next;
p2= p2.next;
}
//p2到达后,删除对应的p1结点
ListNode tmp = p1.next.next;
p1.next=tmp;
return head;
}
}
}
class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}