鏈表: 在單鏈表中刪除指定值的節點


 

問題描述:

給定一個鏈表的頭結點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, 通過這兩個變量的移動、賦值、比較判斷,將“最終頭指針”之后待刪除的節點移除掉。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM