Given a linked list, remove the n-th node from the end of list and
return its head.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.
Follow up:
Could you do this in one pass?
链表操作的题,比较简单,主要主要Bug Free
public ListNode removeNthFromEnd(ListNode head, int n) {
int len=0;
ListNode cur=head;
while(cur!=null){
len++;
cur=cur.next;
}
len=len-n;
ListNode trueHead=new ListNode(0);
trueHead.next=head;
cur=trueHead;
while(len>=1){
cur=cur.next;
len--;
}
cur.next=cur.next.next;
return trueHead.next;
}
上面的方法需要遍历两次链表
也可以一次遍历出
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode trueHead=new ListNode(0);
trueHead.next=head;
ListNode first=trueHead;
ListNode second=trueHead;
for(int i=0;i<n;i++) first=first.next;
while(first.next!=null){
first=first.next;
second=second.next;
}
second.next=second.next.next;
return trueHead.next;
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。