極客時間-數據結構-單鏈表

  單鏈表的兩種創建方式:頭插法尾插法

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();
		

	}

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章