顯示具有 Linked List 標籤的文章。 顯示所有文章
顯示具有 Linked List 標籤的文章。 顯示所有文章

2015年7月22日 星期三

LeedCode:Remove Linked List Elements

題目:

Remove all elements from a linked list of integers that have value val.
Example
Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6
Return: 1 --> 2 --> 3 --> 4 --> 5
找到含有目標值的節點並刪除。
Delete Node in a Linked List中的Linked List定義相同

想法:

這題也卡了有點久,原本是想設一個tempNodePointer指向開頭或結尾的節點,檢查完有目標值就刪掉換下一個,但問題出在,如果沒有目標值,只是純粹換下一個,會把原本的節點給蓋掉。
所以後來選擇比較不直觀的遞迴解。

Accepted Solution:

C#
public class Solution {
    public ListNode RemoveElements(ListNode head, int val) {
            if (head!=null) //該點為空直接傳回null
            {
                while(head.val == val) //如果該點含目標值
                {
                    //刪掉該點
                    if(head.next!=null)head = head.next;  
                    else {
                        head=null;
                        return null;
                        }
                }
                //對該點的下一點做同樣的事
                head.next=RemoveElements(head.next, val);
            }
            else return null;
            
            return head;
    }
}

LeetCode : 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.
Supposed the linked list is 1 -> 2 -> 3 -> 4 and you are given the third node with value 3, the linked list should become 1 -> 2 -> 4 after calling your function.

在給定的Linked List下刪除指定節點,
Linked List定義如下(in C#)
public class ListNode {
    public int val;
    public ListNode next;
    public ListNode(int x) { val = x; }
}

想法:

因為是單向的,無法得知被誰所指定,索性把目標節點改的和他下一個一模一樣,C#就會把目標節點當垃圾收走啦,用題目的例子來說就是變成:1->2->4->4,原本的3所指向的物件就完全沒有參照而被收走了

Accepted Solution:

C#
public class Solution {
    public void DeleteNode(ListNode node) {
        node.val=node.next.val ;
        node.next = node.next.next;              
    }
}