一、鏈表的基本介紹
1、鏈表是以節點形式來存儲;
2、每個節點包含data域和next域(指向下一個節點);
3、鏈表的各個節點不一定是連續存儲,如圖所示的單鏈表(在內存中的存儲):
4、鏈表分爲帶頭結點的鏈表和沒有頭結點的鏈表,根據實際情況確定。
5、帶(頭節點)的單鏈表的邏輯結構圖如下:
二、單鏈表的代碼
定義ListNode,每個ListNode對象就是一個節點:
class ListNode{
public int data;
ListNode next;//指向下一個節點
public ListNode(int data) {
this.data = data;
this.next=null;
}
}
定義MySignalList類,定義頭部:
class MySignalList {
public ListNode head;
public MySignalList() {
this.head = null;
}
}
以下所有方法均在MySignalList類中:
//頭插法
public void addFirst(int data){
ListNode node = new ListNode(data);
if(this.head==null){
this.head=node;
}else{
node.next=this.head;
this.head=node;
}
}
//尾插法
public void addLast(int data){
ListNode node=new ListNode(data);
//因爲head節點不能動,所以定義一個輔助節點cur
//因爲鏈表不爲空,所以存在一個節點, 即:
ListNode cur=this.head;
if(this.head==null){
this.head=node;
}else{
//遍歷鏈表
while(cur.next!=null){
cur=cur.next;
}
cur.next=node;
}
}
// 查找是否包含關鍵字key是否在單鏈表當中
public boolean contains(int key){
ListNode cur =this.head;
while(cur!=null){
if(cur.data==key){
return true;
}
cur=cur.next;
}
return false;
}
//求單鏈表的長度
public int getLength(){
ListNode cur =this.head;
int count=0;
while(cur!=null){
count++;
cur=cur.next;
}
return count;
}
// 任意位置插入,第一個數據節點爲0號下標
public ListNode searchIndex(int index){
ListNode cur=this.head;
int count=0;
while(count<index-1){
count++;
cur=cur.next;
}
return cur ;
}
public boolean addIndex(int index,int data){
if(index<0|index>getLength()){
System.out.println("插入不合法");
return false;
}
if(index==0){
addFirst(data);
return true;
}
ListNode cur= searchIndex(index);
ListNode node = new ListNode(data);
node.next=cur.next;
cur.next=node;
cur=node;
return true;
}
//刪除第一次出現關鍵字爲key的節點
private ListNode searchPre(int key){
ListNode pre=this.head;
while (pre.next!=null){
if(pre.next.data==key){
return pre;
}
pre=pre.next;
}
return null;
}
public void remove(int key){
if(this.head==null){
System.out.println("單鏈表爲空");
return;
}
if(this.head.data==key) {
this.head = this.head.next;
}
ListNode pre=searchPre(key);
if(pre==null){
return;
}
pre.next=pre.next.next;
}
// 刪除所有值爲key的節點
public void removeAllKey(int key){
if(this.head==null){
System.out.println("單鏈表爲空");
return;
}
if(this.head.data==key){
this.head=this.head.next;
}
ListNode pre=this.head;
ListNode cur=this.head.next;
while(cur!=null){
if(pre.next.data==key){
pre.next=cur.next;
cur=cur.next;
}else{
pre=cur;
cur=cur.next;
}
}
}
//打印單鏈表
//打印
public void display(){
ListNode cur =this.head;
while(cur!=null){
System.out.print(cur.data+" ");
cur=cur.next;
}
System.out.println();
}