鏈表:是一種物理存儲結構上非連續存儲結構。
無頭單向非循環鏈表示意圖:
下面就來實現這樣一個無頭單向非循環的鏈表。
1.頭插法
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;
}
2.尾插法
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; //將插入的元素放在最後節點的後一個
}
3.任意位置插入,第一個數據節點爲0號下標
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;
}
計算鏈表長度的方法:
public int size() {
int size = 0;
for(LinkedNode cur = this.head; cur != null; cur = cur.next) {
size++;
}
return size;
}
找到鏈表的某個位置的方法:
private LinkedNode getIndexPos(int index) {
LinkedNode cur = this.head;
for(int i = 0; i < index; i++){
cur = cur.next;
}
return cur;
}
4.查找關鍵字toFind是否包含在單鏈表當中
public boolean contains(int toFind) {
for(LinkedNode cur = this.head; cur != null; cur = cur.next) {
if(cur.data == toFind) {
return true;
}
}
return false;
}
5.刪除第一次出現關鍵字爲key的節點
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;
}
刪除前應該先找到找到要刪除元素的前一個元素:
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;
}
6.刪除所有值爲key的節點
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;
}
7.打印單鏈表
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("]");
}
8.清空單鏈表
public void clear(){
this.head = null;
}