鏈表:
1. 插入節點
2.刪除第n個節點
3.鏈表的長度
4.判斷是否有環
5.鏈表反轉
6.查找鏈表倒數第k個節點
7.查詢單鏈表的中間節點
8.輸出鏈表
節點類:
public class LNode {
int data;
LNode next;
public LNode(int n){
this.data=n;
this.next=null;
}
public LNode(){
}
}
鏈表操作:
public class MyLinkedList {
LNode head=null;
/**
* 向鏈表中插入數據
*/
public void insert(int n){
LNode node=new LNode(n);
if(head==null){
head=node;
return;
}
LNode temp=head;
while(temp.next!=null){
temp=temp.next;
}
temp.next=node;
}
/**
* 鏈表的長度
*/
public int length(){
LNode temp=head;
int i=1;
while(temp.next!=null){
i++;
temp=temp.next;
}
return i;
}
/**
* 刪除第n的節點
*/
public void delete(int n){
if(n<1 || n >length()){
return;
}
int i=0;
LNode p=head;
while(i<n-2 && p.next!=null ){
i++;
p=p.next;
}
p.next=p.next.next;
}
/**
* 判斷鏈表是否有環
* 快慢指針 快指針追的上慢指針
*/
public Boolean hasCycle(){
Boolean flag=false;
LNode p1=head;
LNode p2=head;
while(p1!=null && p2!=null){
p1=p1.next;
p2=p2.next.next;
if(p2==p1){
flag=true;
break;
}
}
return flag;
}
/**
* 鏈表反轉
*/
public void resverse(){
if(head==null && head.next==null){
return;
}
LNode pre=null;
LNode temp=null;
while(head!=null){
temp=head.next;
head.next=pre;
pre=head;
head=temp;
}
this.head=pre;
}
/**
* 查找鏈表倒數第k個節點
* 雙指針法
*/
public LNode reKNode(int k){
if(head==null) return null;
int length=length();
if(length<k){
return null;
}
LNode p=head;
LNode q=head;
//先移動到第k個節點
for(int i=0;i<k;i++){
p=p.next;
}
//兩個指針通知移動 當p走到結尾時 q則爲倒數第k個節點
while(p!=null){
p=p.next;
q=q.next;
}
return q;
}
/**
* 查詢單鏈表的中間節點
* 定義連個節點 一個走一步 一個走兩步
* 當走兩步的爲null時 走一步的則爲中間節點
*/
public LNode searchMiddleNode(){
LNode p1=head;
LNode p2=head;
while(p2!=null && p2.next!=null && p2.next.next!=null){
p1=p1.next;
p2=p2.next.next;
}
return p1;
}
/**
* 輸出鏈表
*/
public void consoleLinkedList(){
LNode temp=head;
while(temp!=null){
System.out.println(temp.data);
temp=temp.next;
}
}
}