2015年7月22日 星期三

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;              
    }
}

沒有留言:

張貼留言