Paste_Image.png
My code:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode removeElements(ListNode head, int val) {
if (head == null)
return null;
while (head != null && head.val == val)
head = head.next;
if (head == null)
return null;
ListNode temp = head;
while (temp.next != null) {
if (temp.next.val == val)
temp.next = temp.next.next;
else
temp = temp.next;
}
return head;
}
}
My test result:
這道題目和剛剛差不多吧吼肥,只不過處理的是鏈表。 也簡單很多麻车。
說個(gè)細(xì)節(jié)缀皱,之前也一直有過以為。
while (head != null && head.val == val)
head = head.next;
這段如果改成:
while (head.val == val && head != null)
head = head.next;
就會報(bào)錯(cuò)动猬。所以說啤斗,編譯器檢查while,if這類括號內(nèi)的內(nèi)容時(shí)(與邏輯)赁咙,會先檢查左邊的再檢查右邊的钮莲,左邊的如果過不了,那就會立刻退出彼水,不會再去看右邊的臂痕,即使右邊犯了嚴(yán)重的錯(cuò)誤,比如空指針猿涨。
而在復(fù)制操作時(shí),編譯器會先檢查右邊的值姆怪,計(jì)算出來后叛赚,在賦給左邊,所以即使某個(gè)值同時(shí)出現(xiàn)在左邊和右邊稽揭,但左邊的將會是新值俺附,而右邊則是舊值。
**
總結(jié):上面的與邏輯處理技巧得記住溪掀。
**
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 ListNode removeElements(ListNode head, int val) {
if (head == null) {
return head;
}
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode pre = dummy;
ListNode curr = dummy.next;
while (curr != null) {
if (curr.val == val) {
pre.next = curr.next;
curr = pre.next;
}
else {
curr = curr.next;
pre = pre.next;
}
}
return dummy.next;
}
}
差不多的做法事镣。
看以前的總結(jié),還是很用心的揪胃。
Anyway, Good luck, Richardo! -- 08/15/2016