码迷,mamicode.com
首页 > 其他好文 > 详细

O(1)时间删除链表中节点

时间:2018-06-17 21:24:41      阅读:168      评论:0      收藏:0      [点我收藏+]

标签:赋值   this   current   public   头结点   删除链表   int   lse   static   

class doDelete{
    static class LNode {
        int data;
        LNode next;
        public  LNode(int data){
            this.data = data;
        }
    }    
    LNode head;
    LNode current;
    public void add(int data){
        if(head==null){
            head = new LNode(data);
            current=head;
        }else{
            current.next=new LNode(data);
            current = current.next;
        }
    }
    public void print(LNode node){
        LNode temp = node;
        if(temp == null) return;
        while(temp!=null){
            System.out.println(temp.data);
            temp = temp.next;
        }
    }
    public LNode delete(LNode head,LNode node){
        if(head==null || node  == null) return null;
        if(node.next != null){
            LNode temp = node.next;
            node.data = temp.data;
            node.next = temp.next;
            return head;
        }else if (head == node){
            return null;
        }else{
            LNode temp = head;
            while(temp.next!=node){
                temp = temp.next;
            }
            temp.next = null;
            return head;
        }
         
    }
    public static void main(String[] args){
        //doDelete r = new doDelete();
        //for(int i =1;i<10;i++){
        //    r.add(i);
        //}
        //r.print(r.head);
        //删除头结点为空
        LNode head = null;
        doDelete r = new doDelete();
//        LNode result = r.delete(head,head);
//        r.print(result);
        
        //删除尾节点不为空
        //for(int i=1;i<10;i++){
        //    r.add(i);
        //}        
        //r.print(r.head);
        //System.out.println();
        //LNode result = r.delete(r.head,r.head.next);
        //r.print(r.head);
        
        //删除尾节点为空,只有一个节点
        // head = new LNode(3);
        //r.print(head);
        //System.out.println("--------------");
        //LNode result = r.delete(head,head);
        //r.print(result);
        
        //删除尾节点,>一个节点
        for(int i=1;i<10;i++){
            r.add(i);
        }
        LNode temp = new LNode(10);
        r.current.next = temp;
        r.print(r.head);
        System.out.println("---------------");
        r.delete(r.head,temp);
        r.print(r.head);
        
        
    }
    

}

算法的整体思路是:

先判断传入参数的情况:如果为空则返回null

判断尾节点是否为空:如果尾节点不为空,则将链表中要删除节点的后一个节点的值赋值给要删除的节点。

如果尾节点为空,则判断该链表是否只有一个节点,如果是只有一个节点,则返回null,

如果不是只有一个节点,则遍历到最末尾的节点,将其删除。

O(1)时间删除链表中节点

标签:赋值   this   current   public   头结点   删除链表   int   lse   static   

原文地址:https://www.cnblogs.com/yingpu/p/9193636.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!