首页 > 编程语言 > 详细

java 实现链表

时间:2019-11-12 22:21:21      阅读:78      评论:0      收藏:0      [点我收藏+]
public class MyList {

    Entry head;

     class Entry {
         Object data;
         Entry next;

         public Entry(Object data) {
             this.data = data;
             this.next = null;
         }
         public Entry(){
             this.data = -1;
             this.next = null;
         }
     }

    public MyList() {
        head = new Entry();
    }

    //不算头节点
    public void show() {
        Entry p = head;
        while (p.next != null) {
            System.out.println(p.next.data);
            p = p.next;
        }
    }

    //不算头节点
    public int size() {
        Entry p = head.next;
        int sum = 0;
        while (p != null) {
            sum++;
            p = p.next;
        }
        return sum;
    }

    //头插法
    public void insertHead(int val){
         Entry p = new Entry(val);
         p.next = head.next;
         head.next = p;
    }
    //尾插法
    public void insrtTail(int val){
         Entry p = new Entry(val);
         //先找出最好一个节点
        Entry temp = head;
        while (temp.next!=null){
            temp = temp.next;
        }
        temp.next = p;
        p.next = null;
    }
    //计算插入位置的节点
    public boolean insertPos(int pos,int val){
         Entry p = new Entry(val);
         if (pos < 0 || pos > size()){
            return false;
         }
         Entry cur = head;
         //先计算出插入的位置
        for (int i =0;i<=pos-1;i++){
            cur = cur.next;
        }
        p.next = cur.next;
        cur.next = p;
        return true;
    }

    public static void main(String args[]){
         MyList myList = new MyList();
//         myList.insertHead(1);
//         myList.insertHead(2);
//         myList.insertHead(3);
//         myList.insertHead(4);

//         myList.insrtTail(1);
//         myList.insrtTail(2);
//         myList.insrtTail(3);
//         myList.insrtTail(4);
        myList.insertPos(0,4);
        myList.insertPos(1,6);
        myList.insertPos(2,3);
        myList.insertPos(3,1);
        myList.show();
    }
}

 https://blog.csdn.net/qq_37937537/article/details/80101744 

java 实现链表

原文:https://www.cnblogs.com/Andrew520/p/11844875.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!