鏈表:是一種物理存儲結構上非連續存儲結構。node
無頭單向非循環鏈表示意圖:
下面就來實現這樣一個無頭單向非循環的鏈表。數據結構
public void addFirst(int elem) { LinkedNode node = new LinkedNode(elem); //建立一個節點 if(this.head == null) { //空鏈表 this.head = node; return; } node.next = head; //不是空鏈表,正常狀況 this.head = node; return; }
public void addLast(int elem) { LinkedNode node = new LinkedNode(elem); if(this.head == null) { //空鏈表 this.head = node; return; } LinkedNode cur = this.head; //非空狀況建立一個節點找到最後一個節點 while (cur != null){ //循環結束,cur指向最後一個節點 cur = cur.next; } cur.next = node; //將插入的元素放在最後節點的後一個 }
public void addIndex(int index,int elem) { LinkedNode node = new LinkedNode(elem); int len = size(); if(index < 0 || index > len) { //對合法性校驗 return; } if(index == 0) { //頭插 addFirst(elem); return; } if(index == len) { //尾插 addLast(elem); return; } LinkedNode prev = getIndexPos(index - 1); //找到要插入的地方 node.next = prev.next; prev.next = node; }
計算鏈表長度的方法:ide
public int size() { int size = 0; for(LinkedNode cur = this.head; cur != null; cur = cur.next) { size++; } return size; }
找到鏈表的某個位置的方法:this
private LinkedNode getIndexPos(int index) { LinkedNode cur = this.head; for(int i = 0; i < index; i++){ cur = cur.next; } return cur; }
public boolean contains(int toFind) { for(LinkedNode cur = this.head; cur != null; cur = cur.next) { if(cur.data == toFind) { return true; } } return false; }
public void remove(int key) { if(head == null) { return; } if(head.data == key) { this.head = this.head.next; return; } LinkedNode prev = seachPrev(key); LinkedNode nodeKey = prev.next; prev.next = nodeKey.next; }
刪除前應該先找到找到要刪除元素的前一個元素:code
private LinkedNode seachPrev(int key){ if(this.head == null){ return null; } LinkedNode prev = this.head; while (prev.next != null){ if(prev.next.data == key){ return prev; } prev = prev.next; } return null; }
public void removeAllkey(int key){ if(head == null){ return; } LinkedNode prev = head; LinkedNode cur = head.next; while (cur != null){ if(cur.data == key){ prev.next = cur.next; cur = prev.next; } else { prev = cur; cur = cur.next; } } if(this.head.data == key){ this.head = this.head.next; } return; }
public void display(){ System.out.print("["); for(LinkedNode node = this.head; node != null; node = node.next){ System.out.print(node.data); if(node.next != null){ System.out.print(","); } } System.out.println("]"); }
public void clear(){ this.head = null; }