Java——連結串列
阿新 • • 發佈:2018-11-05
簡單用java寫了個連結串列,對於傳入異常引數沒有處理,供大家參考。個人覺得比c語言實現起來簡單,因為不用去刻意理解指標了。雖然java沒有指標,但是實際上對物件的訪問就是通過指標來實現的。
對連結串列的操作比較難的就是反轉,近期會再寫一篇關於連結串列反轉的。
/** * 定義一個連結串列類 * 實現頭插、尾插、任意位置插入、指定位置查詢 * 指定位置刪除、反轉、列印、取長度操作 */ final class Link{ private Node head; Link(){ head = new Node(); } /** * 將結點定義為一個私有內部類 */ private class Node{ public int data; public Node next; Node(){ next = null; } Node(int data){ this.data = data; } } /**尾插 */ public void InsertTail(int data){ Node n = new Node(data); Node cur = this.head; while(cur.next!=null){ cur = cur.next; } cur.next = n; } /**頭插 */ public void InsertHead(int data){ Node n = new Node(data); n.next = head.next; head.next = n; } /**取長度 */ public int getLenth(){ int count = 0; Node cur = head; while(cur.next!=null){ cur = cur.next; count++; } return count; } /**制定位置插入 */ public void Insert(int data,int position){ Node n = new Node(data); Node cur = this.head; for(int i = 0;i<position;i++){ cur = cur.next; } n.next = cur.next; cur.next = n; } /**刪除指定位置結點 */ public void del(int position){ Node cur = this.head; for(int i = 0;i<position;i++){ cur = cur.next; } cur.next = cur.next.next; } /** * 使用頭插來反轉連結串列 * 將下一個節點插在前面 * 再將後面的結點刪除 */ public void reverse(){ Node cur = this.head; int i = 0; while(cur.next!=null){ this.InsertHead(cur.next.data); cur = cur.next; this.del(i); i++; } } /** * 迭代法進行反轉 */ public void reverse2(){ Node prev = null; Node now = head.next; Node next = null; while(now!=null){ next = now.next; now.next = prev; prev = now; now = next; } head.next = prev; } /**指定位置查詢 */ public int search(int position){ Node cur = this.head; for(int i = 0;i<=position;i++){ cur = cur.next; } return cur.data; } /**列印連結串列 */ public void display(){ Node cur = this.head; while(cur.next!=null){ System.out.print(cur.next.data); cur = cur.next; } } }