leetcode 19:Remove Nth Node From End of List

題目描述

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;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章