單鏈表的常用操作
阿新 • • 發佈:2018-11-01
生活果然是需要一點刺激的,從今天開始,我一定要好好寫部落格!!
首先連結串列的節點定義:
class Node{
public int data;
public Node next;
}
以下操作假設單鏈表有頭結點(head!=null)。
1、末尾新增節點
public void addNode(Node node){
Node current=head;//head是單鏈表的頭結點
while(current.next!=null){
current=current.next;
}
current.next=node;
}
2、指定位置插入節點
public void insert(Node node,int idx){ Node current =head; if(idx<1||idx>length()+1){ print("插入位置不合法") } int temp=1; while(current.next!=null){ if(temp<idx){//遍歷單鏈表,找到插入位置 current=current.next; temp++; }else{ node.next=current.next; current.next=node; return ; } } }
3、刪除指定位置的節點
public void delete(int idx){
Node current =head;
if(idx<1||idx>length()+1){
print("刪除位置不合法")
}
int temp=1;
while(current.next!=null){
if(temp<idx){//遍歷單鏈表,找到刪除位置
current=current.next;
temp++;
}else{
current.next=current.next.next;
return ;
}
}
}
4.1、單鏈表逆置(遞迴),舉個例子,逆置a->b->c->d
public void reverse(Node current,Node head){//head儲存逆置後的頭結點
if(current.next==null){
head=current;
}else{
Node pNext=current.next;
reverse(pNext,head);//逆置b->c->d
pNext.next=current;
current.next=null;
}
}
4.2、單鏈表逆置(非遞迴)
public Node reverse(Node head){
Node p=head.next;
head.next=null;
Node q;//q指向下一節點,保證連結串列的不斷裂,,head永遠指向頭結點
while(p){
q=p.next;
p.next=head.next;
head.next=p;
p=q;
}
}