1. 程式人生 > >LeetCode刷題Easy篇刪除單鏈表中的元素Delete Node in a Linked List

LeetCode刷題Easy篇刪除單鏈表中的元素Delete Node in a Linked List

題目

Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.

Given linked list -- head = [4,5,1,9], which looks like following:

    4 -> 5 -> 1 -> 9

Example 1:

Input: head = [4,5,1,9], node = 5
Output: [4,1,9]
Explanation: 
You are given the second node with value 5, the linked list   should become 4 -> 1 -> 9 after calling your function.

Example 2:

Input: head = [4,5,1,9], node = 1
Output: [4,5,9]
Explanation: You are given the third node with value 1, the linked list
             should become 4 -> 5 -> 9 after calling your function.

Note:

  • The linked list will have at least two elements.
  • All of the nodes' values will be unique.
  • The given node will not be the tail and it will always be a valid node of the linked list.
  • Do not return anything from your function.

這道題目以前做過一次,寫完後發現不一樣,這個沒有給頭節點,要直接刪除指定node。

為了複習這個演算法,我先寫了一下有head節點的情況,程式碼出現了幾個小問題。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode removeElements(ListNode head, int val) {
         ListNode curr=head;
        ListNode pre=null;
        while(curr!=null){
            if(curr.val==val){
                if(pre==null){
                    head=head.next;
                }
                else{
                   ListNode tmp=curr.next;
                   pre.next=tmp;
                   
                }
               
            }
            pre=curr;
            curr=curr.next;
    }
        return head;
}
}

相等的情況下pre=curr不要執行。相等的節點會被移除,所以curr移動後,pre仍舊是原來的pre。修改後如下:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode removeElements(ListNode head, int val) {
         ListNode curr=head;
        ListNode pre=null;
        while(curr!=null){
            if(curr.val==val){
                if(pre==null){
                    head=head.next;
                }
                else{
                    pre.next=curr.next;
                    
                } 
            }
            //pre指標在相等的情況下需要移動
            else{
                 pre=curr;
            }
           
            curr=curr.next;
    }
        return head;
}
}