java 实现链表
阅读原文时间:2023年07月15日阅读:1

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

手机扫一扫

移动阅读更方便

阿里云服务器
腾讯云服务器
七牛云服务器

你可能感兴趣的文章