链表: 在单链表中删除指定值的节点


 

问题描述:

给定一个链表的头结点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