双向链表 添加与遍历

package com.pay.test;
//定义节点
public class DoubleLinkedList {

    //初始化头节点
    private  HeroNode head=new HeroNode(0,"","");

    //返回节点头
    public HeroNode getHead(){
        return head;
    }

    /**
     * 双向链表节点遍历
     */
    public  void  list(){
        if(head.next==null){
            System.out.println("链表为空");
            return;
        }

        HeroNode temp= head.next;
       while (true){
           if(temp==null){
                break;
           }
           //输出节点信息
           temp.print();
           temp=temp.next;

       }
    }


    public void add(HeroNode heroNode2 ){
          HeroNode temp=head;
           while (true){
               if(temp.next==null){
                    break;
               }
              temp= temp.next;
           }
           temp.next=heroNode2;
           heroNode2.pre=temp;
    }


}
package com.pay.test;

public class DoubleLinkedListTest {
    public static void main(String[] args) {

        HeroNode heroNode1=new HeroNode(1,"张三","张三风");
        HeroNode heroNode2=new HeroNode(2,"李四","李四一");
        HeroNode heroNode3=new HeroNode(3,"王五","王老五");
        HeroNode heroNode4=new HeroNode(4,"赵六","赵老六");
        HeroNode heroNode5=new HeroNode(5,"刘七","刘老七");
        HeroNode heroNode6=new HeroNode(6,"王八","王老八");
        DoubleLinkedList list=new DoubleLinkedList();
        list.add(heroNode1);
        list.add(heroNode2);
        list.add(heroNode3);
        list.add(heroNode4);
        list.add(heroNode5);
        list.add(heroNode6);
        list.list();




    }

}

  

  

posted @ 2023-01-29 19:55  郎小乐  阅读(36)  评论(0编辑  收藏  举报