leetcode 18刪除鏈表的倒數第n個結點

示例:
給定一個鏈表: 1->2->3->4->5, 和 n = 2.
當刪除了倒數第二個節點後,鏈表變爲 1->2->3->5.

如上,正常思路:鏈表的長度———>要刪除的位置的前一個———>刪除

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        if(head == null) 
            return head;
        ListNode temp = head;
        int length = 1;
        //統計鏈表個數
        while(temp.next != null){
            temp = temp.next;
            length++;
        }
        //計算位置
        int pos = length - n + 1;
        //刪除結點
        if(pos == 1)
            return head.next;
        temp = head;
        for(int i = 1; i < pos - 1; i++)
            temp =temp.next;
        //刪除結點
        temp.next = temp.next.next;
        return head;    
    }
}

進階: 只掃描一次  雙指針!!!一個fast一個low,一定要注意數字!!!繞來繞去

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        // if(head == null) 
        //     return head;
        // ListNode temp = head;
        // int length = 1;
        // //統計鏈表個數
        // while(temp.next != null){
        //     temp = temp.next;
        //     length++;
        // }
        // //計算位置
        // int pos = length - n + 1;
        // //刪除結點
        // if(pos == 1)
        //     return head.next;
        // temp = head;
        // for(int i = 1; i < pos - 1; i++)
        //     temp =temp.next;
        // //刪除結點
        // temp.next = temp.next.next;
        // return head;   

        //指針指來指去指不清
        if(head == null)
            return head;
        ListNode fast = head;
        ListNode low = head;
        for(int i = 0; i < n; i++)
            fast = fast.next;
        if(fast == null)
            return head.next;
        while(fast.next != null){
            fast = fast.next;
            low =low.next;
        }
        low.next = low.next.next;
        return head;


        

    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章