1. 程式人生 > 其它 >JAVA資料結構--連結串列1

JAVA資料結構--連結串列1

技術標籤:JAVA連結串列java資料結構

JAVA單向無頭連結串列

1.概念

連結串列作為一種物理儲存結構上非連續的儲存結構,資料元素的邏輯順序是通過連結串列中的引用連結順序實現的。
連結串列直觀的理解就是一連串的資料,每個資料都能引導向下一個資料,也就是說資料是儲存在節點上,而節點能夠指向下一個資料節點

2.程式碼實現

class Node{
    public int data;
    public Node next;
    public Node(){

    }
    public Node(int d){
        this
.data = d; } } class LinkedList{ private Node head; public LinkedList(){ } public LinkedList(int data){ this.head.data=data; } //列印整個連結串列 public void display(){ if (this.head==null){ System.out.println("null"); } Node cur =
this.head; while(cur!=null){ System.out.print(" "+cur.data); cur = cur.next; } } //頭插法,往當前連結串列的頭部插入一個節點, //首先要建立新節點接收傳入的值,然後將當前首節點傳入新節點,將新節點設為首節點 public void addFirst(int data){ Node ret = new Node(data); if (this.head==null)
{ this.head=ret; return; } ret.next = this.head; this.head = ret; } //尾插法,建立節點遍歷整個連結串列,到最後一個節點其next指向空, //當此節點的指向為空時,代表遍歷到最後一個節點,建立新節點儲存進來的資料, //將當前的最後一個節點指向新的節點,連結串列串在一起結束 public Node getLast(){ Node cur = this.head; while(cur.next!=null){ cur = cur.next; } return cur; } public void addLast(int data){ if (this.head==null){ addFirst(data); return; } Node ret = new Node(data); Node cur = getLast(); cur.next=ret; } //檢視連結串列是否包含某個元素 public boolean contains(int key){ Node cur = this.head; while (cur.next!=null){ if (cur.data==key){ return true; }else { cur=cur.next; } } return false; } //獲取連結串列長度,通過計數器遍歷連結串列 public int size(){ int count = 1; Node cur = this.head; while(cur.next!=null){ cur=cur.next; count++; } return count; } //插入連結串列的任意位置,首先判斷插入位置是否合理,不合理返回失敗 //插入位置合理則遍歷連結串列到插入位置的前一節點,將插入的節點與後續節點穿起來 //再將這個子連結串列與前面的子連結串列穿起來 public boolean addIndex(int index,int data){ if (index<0||index>this.size()){ System.out.println("此位置不合法"); return false; }else if (index==0){ addFirst(data); return true; }else if(index==size()){ addLast(data); return true; } Node ret = new Node(data); Node cur = this.head; int count = 1; while (count!=index-1){ cur =cur.next; count++; } ret.next = cur.next; cur.next=ret; return true; } //刪除第一次出現的Key public void remove(int key){ Node cur = this.head; while (cur.next.data!=key){ cur = cur.next; } cur.next = cur.next.next; } //刪除所有出現的Key public void removeAllKey(int key){ Node cur = this.head; while(cur.next!=null){ if (cur.next.data==key){ cur.next=cur.next.next; }else { cur = cur.next; } } } public void clear(){ this.head=null; } }

3.測試示例

public class Demo {
    public static void main(String[] args){
        LinkedList Llist=new LinkedList();
        Llist.addFirst(2);
        Llist.addLast(3);
        Llist.addLast(4);
        Llist.addIndex(2,1);
        Llist.addIndex(4,4);
        Llist.addIndex(4,3);
        System.out.println(Llist.size());
        Llist.display();
        Llist.remove(3);
        System.out.println();
        Llist.display();
        Llist.removeAllKey(4);
        System.out.println();
        Llist.display();
        Llist.clear();
        System.out.println();
        Llist.display();
    }
}

結果