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;
}
}
}
這次作業(yè)不難溢十,一開始想著怎么可能刪除結(jié)點(diǎn)呢,后來覺得是改數(shù)值达吞,這樣就簡(jiǎn)單很多了张弛。
**
總結(jié):貌似是第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;
}
}
題目不難。
現(xiàn)在才知道瞒大,原來還有一種效率更高的做法螃征。比如,
1 2 3 4 5 6
我要?jiǎng)h除 3
那么將 3 改成 4 然后讓該結(jié)點(diǎn)指向5
1 2 4 5 6
那么復(fù)雜度就是 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;
}
}
突然發(fā)現(xiàn)這個(gè)做法好蠢⌒锏纾看了以前的總結(jié)才記起還有一種 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