删除链表中指定节点

删除链表中指定节点

思路:利用其他结构(这里利用栈结构)存放链表中除要删除的节点外的其他节点。依次将链表元素放入栈中,当遇到要删除的元素时跳过,最后将栈中元素重新连接成链表。

具体代码

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);
    }
}

测试结果

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值