Leetcode - Delete Node in a Linked List

Leetcode - Delete Node in a Linked List_第1张图片

My code:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public void deleteNode(ListNode node) {
        if (node == null)
            return;
        ListNode temp = node;
        while (temp.next != null) {
            temp.val = temp.next.val;
            if (temp.next.next == null) {
                temp.val = temp.next.val;
                temp.next = null;
                break;
            }
            else
                temp = temp.next;
        }
    }
}

这次作业不难,一开始想着怎么可能删除结点呢,后来觉得是改数值,这样就简单很多了。

**
总结:貌似是第50题。
只不过最近做了好多 easy 题目啊。。。
**

Anyway, Good luck, Richardo!

My code:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public void deleteNode(ListNode node) {
        if (node == null)
            return;
        ListNode pre = node;
        while (node.next != null) {
            pre = node;
            ListNode next = node.next;
            node.val = next.val;
            node = next;
        }
        pre.next = null;
        return;
    }
}

题目不难。

现在才知道,原来还有一种效率更高的做法。比如,
1 2 3 4 5 6
我要删除 3
那么将 3 改成 4 然后让该结点指向5
1 2 4 5 6
那么复杂度就是 O(1)了。

妙!

Anyway, Good luck, Richardo!

My code:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public void deleteNode(ListNode node) {
        if (node == null) {
            return;
        }
        
        ListNode dummy = new ListNode(-1);
        dummy.next = node;
        ListNode curr = dummy.next;
        ListNode pre = dummy;
        
        while (curr.next != null) {
            curr.val = curr.next.val;
            curr = curr.next;
            pre = pre.next;
        }
        
        pre.next = null;
    }
}

突然发现这个做法好蠢。看了以前的总结才记起还有一种 O(1)的做法。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public void deleteNode(ListNode node) {
        if (node == null) {
            return;
        }
        
        node.val = node.next.val;
        node.next = node.next.next;
    }
}

Anyway, Good luck, Richardo! -- 08/15/2016

你可能感兴趣的:(Leetcode - Delete Node in a Linked List)