單鏈表的兩種創建方式:頭插法尾插法
package data.structure.link;
public class SingleLink {
private int num;
private Node head;
public SingleLink(int num,Node head) {
this.num=num;
this.head=head;
}
/*
* 尾插法
*/
public void createHeadInsert() {
Node tail=head;
for(int i=0;i<num;i++) {
Node p=new Node();//創建一個新節點
p.data=i;//設置數據域
p.next=null;
tail.next=p;
tail=p;
}
}
/*
* 前插法
*/
public void beforeHeadInsert() {
Node tail=null;
for(int i=0;i<num;i++) {
Node p=new Node();//創建一個新節點
p.data=i;//設置數據域
p.next=tail;
tail=p;
}
head.next=tail;
}
/*
* 鏈表輸出
*/
public void pop() {
while(head!=null) {
Node node=head.next;
if(node!=null) {
System.out.print(node.data+" ");
head=node;
}else {
break;
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Node head=new Node();
SingleLink list=new SingleLink(10,head);
System.out.println("前插法創建大小爲10的一個鏈表:0 1 2 3 4 5 6 7 8 9");
list.createHeadInsert();
System.out.print("前插法創建鏈表輸出");
list.pop();
System.out.println("\r後插法創建大小爲10的一個鏈表:0 1 2 3 4 5 6 7 8 9");
head=new Node();
list=new SingleLink(10,head);
list.beforeHeadInsert();
System.out.print("後插法創建鏈表輸出");
list.pop();
}
}