删除单链表中指定元素

在0(1)时间内删除链表节点
每个节点只有后继没有前驱
分析:
要考虑三种情况,链表只有一个元素、要找的这个节点的next为空他在链表尾部或者没有,要找的节点在中间

尾部的话用笨办法去找
如果在中间,把他的下一个节点的值给他,然后删除下一个节点就行
如果是就一个元素,删除头部返回为空。

    public static class Node{
        Node next;
        int val;
        public Node(int val,Node pnext){
            this.val = val;
            this.next = pnext;
        }
        public Node(){}
    }
    public static Node deleteNode(Node head,Node pnode){
        if(head == null||pnode == null){
            return null;
        }//代码鲁棒
        if(head == pnode){
            pnode = null;
            head = null;

            return head;

        }
        else if(pnode.next!=null){//要删的节点是中间节点
            pnode.val = pnode.next.val;//把要删的节点的值给他的下一个节点
            pnode.next = pnode.next.next;//删掉他的下一个节点
        }else{//如果这节点在最后,因为你不知道他的下一个节点是什么又没有他的前驱来确定他的位置,只能在
            //从头到尾开始找直到最后,找到删掉或者没有这个节点
            Node tempNode = head ;

            while(tempNode.next!=pnode && tempNode!=null){
                tempNode = tempNode.next;
            }
            if(tempNode==null){
                System.out.println("No this Node");
                return head;
            }
            tempNode.next = null;

            pnode = null;
        }

        return head;
    }
    public static void travelist(Node head){
        Node curr = head;
        while(curr!=null){
            System.out.print(curr.val+" ");
            curr = curr.next;
        }
        System.out.println();
    }

    public static void main(String[] args) {
        Node p5 = new Node (5,null);
        Node p4 = new Node (4,p5);
        Node p3 = new Node (3,p4);
        Node p2 = new Node (2,p3);
        Node p1 = new Node(1,p2);


        Node result = deleteNode(p5,p5);
        Node result1 = deleteNode(p1,p2);
        Node result2 = deleteNode(p1,p3);
        Node result3 = deleteNode(p1,p4);
        Node result4 = deleteNode(p1,p5);

        travelist(result);

    }

操蛋?????

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值