Remove Nth Node From End of List QuestionEditorial Solution
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.
我的代码,速度慢 容易理解
ArrayList<ListNode> list=new ArrayList<>();
while(head!=null){
list.add(head);
head=head.next;
}
list.remove(list.size()-n);
ListNode ln=new ListNode(0);
ListNode ln2=new ListNode(0);
ln2=ln;
for (ListNode listNode : list) {
ln.next=new ListNode(listNode.val);
ln=ln.next;
}
return ln2.next;
}
大神的代码
采用:.Two pointers。 利用快慢指针,快指针先走n步,然后一起走,快的下一步到终点了,慢的到达要删除的前一位;
非常nice
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode start = new ListNode(0);
ListNode slow = start, fast = start;
slow.next = head;
//Move fast in front so that the gap between slow and fast becomes n
for(int i=1; i<=n+1; i++) {
fast = fast.next;
}
//Move fast to the end, maintaining the gap
while(fast != null) {
slow = slow.next;
fast = fast.next;
}
//Skip the desired node
slow.next = slow.next.next;
return start.next;
}