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: 遍历一般单链表 ,用一个hash表来存储每一个结点是在单链表中的第几个结点,遍历完后从hash表中取出要删除的结点的前一个结点,然后删除该结点。但是要注意删除的是单链表中第一个结点的时候,这个时候就从hash表中取不出来该结点的前一个结点,这个情况要作分开处理。
思路2:采用两个指针p,q,两个指针的距离相差n,首先p和q都是指向head的,然后遍历单链表移动q,使之指向第n和结点,然后p和q就同时向后走,直到q指向最后一个结点,此时p指向的就是要删除结点的前一个结点,然后删除即可。但是同样要注意的是要删除的结点是第一个结点的时候,这时候说明当q移动n步之后,q是为空的。
/**
* 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) {
ListNode p=head;
if(p==null) return null;
Map<Integer,ListNode> ht=new HashMap<Integer,ListNode>();
int i=1;
ListNode q=null;
while(p!=null)
{
ht.put(i, p);
i++;
p=p.next;
}
if(i==n+1)
{ head=head.next;
return head;
}
if(i>n+1)q=ht.get(i-n-1);
if(q.next!=null) q.next=q.next.next;
return head;
}
}