問題描述:
給定一個鏈表的頭結點head和一個整數num,請實現函數將值為num的節點全部刪除。
例如:鏈表為1->2->3->5->3->6->null,num=3,調整后的鏈表為: 1->2->5->6->null
算法實現:
public class Node {
public int value;
public Node next;
public Node(int value) {
this.value = value;
}
}
算法1:
public Node removeValue1(Node head, int num) {
Stack<Node> stack = new Stack<>();
while (head != null) {
if(head.value != num) {
stack.push(head);
}
head = head.next;
}
while (!stack.isEmpty()) {
stack.peek().next = head;
head = stack.pop();
}
return head;
}
算法2:
public Node removeValue2(Node head, int num) {
while (head != null) {
if(head.value != num) {
break;
}
head = head.next;
}
Node pre = head;
Node cur = head;
while (cur != null) {
if(cur.value == num) {
pre.next = cur.next;
} else {
pre = cur;
}
cur = cur.next;
}
return head;
}
算法解析:
解法1:
需要一個額外的棧空間,通過將“有效的數據入棧”,之后在出棧的過程中重新“鏈節點成表”,要注意的是出棧時“head”指向的移動。
解法2:
先通過判斷和必要的移動,找到“最終的頭結點”,設置兩個臨時變量指向head, 通過這兩個變量的移動、賦值、比較判斷,將“最終頭指針”之后待刪除的節點移除掉。