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)复杂度)
代码:
/**
* 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;
}
}