題目描述
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.
題目大意:刪除鏈表的倒數第N個結點。要求只遍歷一次。
解題思路
用兩個指針,第一個指針先走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) {
if(head == null || n == 0)
return null;
ListNode start = new ListNode(0);
start.next = head;
ListNode pHead = start;
ListNode pBehind = start;
for(int i =0 ; i< n;i++){
pHead = pHead.next;
}
while(pHead.next!=null){
pHead=pHead.next;
pBehind = pBehind.next;
}
pBehind.next = pBehind.next.next;
return start.next;
}
}