发布于2021-03-07 21:38 阅读(1138) 评论(0) 点赞(21) 收藏(5)
删除链表中指定节点
思路:利用其他结构(这里利用栈结构)存放链表中除要删除的节点外的其他节点。依次将链表元素放入栈中,当遇到要删除的元素时跳过,最后将栈中元素重新连接成链表。
具体代码
public class removeValue {
public static class Node{
public int val;
public Node next;
public Node(int val){
this.val = val;
}
}
public static Node remove(Node head,int num){
Stack<Node> stack = new Stack<>();
while(head != null){
if(head.val != num){
stack.push(head);
}
head = head.next;
}
//将栈中元素重新连接成链表
while(!stack.isEmpty()){
//将栈中元素从栈顶依次指向上面,刚开始栈顶元素指向空,栈底元素成为链表头节点
stack.peek().next = head;
head = stack.pop();
}
return head;
}
public static void print(Node head){
if(head==null){
return ;
}
while(head != null){
System.out.print(head.val+" ");
head = head.next;
}
}
public static void main(String[] args) {
Node head = new Node(1);
head.next = new Node(2);
head.next.next = new Node(3);
head.next.next.next = new Node(4);
Node node = remove(head, 3);
print(node);
}
}
测试结果
原文链接:https://blog.csdn.net/thunder_666/article/details/114398114
作者:javabb
链接:http://www.javaheidong.com/blog/article/110799/fc48031a208725c8d7fa/
来源:java黑洞网
任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任
昵称:
评论内容:(最多支持255个字符)
---无人问津也好,技不如人也罢,你都要试着安静下来,去做自己该做的事,而不是让内心的烦躁、焦虑,坏掉你本来就不多的热情和定力
Copyright © 2018-2021 java黑洞网 All Rights Reserved 版权所有,并保留所有权利。京ICP备18063182号-2
投诉与举报,广告合作请联系vgs_info@163.com或QQ3083709327
免责声明:网站文章均由用户上传,仅供读者学习交流使用,禁止用做商业用途。若文章涉及色情,反动,侵权等违法信息,请向我们举报,一经核实我们会立即删除!