自己手写一个双向链表

看书再多不如亲自动手,下面就是我自己实现的一个双向链表

public class MyLinked {

    private Node head;
    private Node tail;
    public int len;

    private static  class  Node{
        private Node prev;
        private   Object data;
        private   Node next;
        public  Node(Object data){
            this.data=data;
        }
        public  Node(Object data,Node next,Node prev){
            this.data=data;
            this.next=next;
            this.prev=prev;
        }
    }


    /**
     * 链表中添加元素
     * @param data
     */
     public  void addData(Object data){
        if (head==null){
            head=new Node(data,null,null);
            tail=head;
            len=len+1;
        }else{
            Node newNode=new Node(data,null,tail);
            tail.next=newNode;
            tail=newNode;
            len=len+1;
        }
     }

      /**
     * 在指定位置的后面插入元素,如果指定位置大于当前链表长度,则将元素添加到链表结尾。
     * 如果当前链表为空,则将元素设置为链表的头结点
     * @param data
     * @param index
     */
     public void addData(Object data,int index){
         if (len==0){
             head=new Node(data,null,null);
             tail=head;
             len=len+1;
         }
         if (index>len){
             Node newNode=new Node(data,null,tail);
             tail.next=newNode;
             tail=newNode;
             len=len+1;
         }
         else {
             int i=0;
             Node temp=head;
             while (temp!=null){
               while (++i==index){
                     Node newNode=new Node(data,temp.next,temp);
                     temp.next=newNode;
                     len=len+1;
                     break;
                 }
                 temp=temp.next;
             }
         }
     }


    /**
     * 从前遍历打印链表元素
     */
    public void traversingDataFromIndex(){
        Node temp=head;
        if (temp==null){
            System.out.println("当前链表为空");
        }else{
            while (temp!=null){
                System.out.println(temp.data);
                temp=temp.next;
            }
        }
     }

    /**
     * 后序遍历打印
     */
    public void  traversingDataFromLast(){
         Node temp=tail;
         if (temp==null){
             System.out.println("当前链表为空");
         }else{
             while (temp!=null){
                 System.out.println(temp.data);
                 temp=temp.prev;
             }
         }
     }


    public static void main(String[] args) {
        MyLinked myLinked=new MyLinked();
        for (int i=0;i<10;i++){
            myLinked.addData(i);
        }
        myLinked.traversingDataFromIndex();
        myLinked.traversingDataFromLast();
    }
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值