鏈表是很多的數據結構的基礎,比如說:隊列,棧,二叉樹,優先級隊列等等,而鏈表也是很多公司面試和筆試的常考題。
鏈表的基本操作包括:判斷是否爲空,頭部插入,尾部插入,根據key值查找,根據key值刪除,遍歷鏈表。
當然稍微複雜一點的操作還包括:鏈表的逆序,鏈表的排序等等。
在鏈表中,包含兩個類:Node(節點)
package com.qiao.lb;
public class Node {
public long data;
public Node next;
public Node(long data){
this.data=data;
}
public void displayLink(){
System.out.print("{"+data+"},");
}
}
當然這個Node類可以根據需要變得很複雜。
LinkList類:
LinkList類中只包含一個數據項,即對鏈表中第一個鏈節點的引用,叫做first,它是唯一的鏈表需要維護的永久信息,用以定位所有其他的鏈節點。從first出發,沿着鏈表通過每個鏈節點的next字段,就可以找到其他的鏈節點:
class LinkList{
private Link first;
public void LinkList(){
first=null;//表示目前爲止鏈表中沒有數據項,如果有,first字段中應該存有對第一個鏈接點的引用值
}
}
在LinkList類中包括對鏈表的一系列操作,包括增刪改查等等。
其中最核心的是insertFirst()方法和insertLast()方法,其方法中對鏈表的操作思路在其他的方法會用到。
不多說了,把全部的代碼粘貼如下(具體的操作大家可以參考我的資源《Java數據結構和算法》這本書):
package com.qiao.lb;
public class LianBiao {
//最好不要用尾插法,因爲每次尾插法都需要遍歷整個鏈表
private Node first;
public LianBiao(){
first=null;
}
public boolean isEmpty(){
return first==null;
}
public void insertFirst(long data){
Node newNode=new Node(data);
newNode.next=first;
first=newNode;
}
public void insertLast(long data){
Node newNode=new Node(data);
Node current=first;
if(current==null){
first=newNode;
}else{
while(current.next!=null){
current=current.next;
}
current.next=newNode;
}
}
public Node deleteFirst(){
Node temp=first;
if(!isEmpty()){
first=first.next;
}
return temp;
}
public void displayList(){
Node current=first;
while(current!=null){
current.displayLink();
current=current.next;
}
System.out.println();
}
public Node find(long key){//找到第一個與key值相同的節點
Node current=first;
while(current!=null){
long data=current.data;
if(key==data){
return current;
}else{
current=current.next;
}
}
return current;
}
public Node delete(long key){
Node current=first;//表示當前節點,同時也表示要刪除的節點
Node prior=current;
while(current!=null){
long data=current.data;
if(data==key){
Node temp=current;
prior.next=current.next;
return current;
}else{
prior=current;
current=current.next;
}
}
return current;
}
}
下面是測試代碼:
package com.qiao.lb;
public class LinkListTest {
public static void main(String[] args) {
LianBiao biao=new LianBiao();
biao.insertLast(9);
biao.insertLast(8);
biao.insertLast(7);
biao.insertLast(6);
biao.insertLast(5);
biao.insertLast(4);
biao.insertLast(3);
biao.insertLast(2);
biao.displayList();
System.out.println("------------------------------------");
biao.delete(10);
biao.displayList();
System.out.println("------------------------------------");
biao.deleteFirst();
biao.displayList();
System.out.println("------------------------------------");
Node node=biao.find(5);
// System.out.println(node.data);
System.out.println("------------------------------------");
biao.insertLast(10);
biao.displayList();
}
}