题目:
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.(意思是O(n)复杂度)
刚开始只想到用两个指针,中间隔n-1步,当走在前面的指针到达尾部时,那么后一个节点一定指向倒数第n个节点。这样还得记录倒数第n个节点的前驱节点,从而才能删除倒数第n个节点。但是,这样遇到的问题是,如果指向的该倒数第n个节点是head节点(没有前驱节点了),那么就没法删除了。改进的方法就是,从一开始就新建一个节点behindhead,使其指向头结点。最后返回的时候返回behindhead.next就好了
代码:
/**
* 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) {
//新建一个节点指向head
ListNode behindhead = new ListNode(0);
behindhead.next = head;
//建两个指针,指针ahead一个指向head节点
ListNode ahead = head;
//指针behind指向behindhead节点
ListNode behind = behindhead;
//指针ahead需要向前移动n-1步
for(int i=0; i<n-1; i++){
if(ahead.next!=null){
ahead = ahead.next;
}
}
//当指针ahead没有到达尾部时,指针ahead和behind都往前移动
while(ahead.next!=null){
ahead = ahead.next;
behind = behind.next;
}
//删除behind后面的节点
behind.next = behind.next.next;
return behindhead.next;
}
}