1. 程式人生 > >java建立單鏈表的兩種方式

java建立單鏈表的兩種方式


/**
 * 
 */
/**   
 * @author jueying:   
 * @version 建立時間:2018-10-23 下午01:26:47   
 * 類說明   
 */
/**
 * @author jueying
 *
 */
public class Test {
	
	int size=0;//大小
	static Node headNode;
	
    int i=0;
	class Node{
		private Node next;//指標
		
		private int data;//資料域
		
	}
	
	//尾插法建立單鏈表  佇列形式先進先出
	public void fun(Node node,int data){
		if(i<=10){
			Node newNode=new Node();//建立新的結點
			newNode.data=i;//設定資料域
			newNode.next=null;
			node.next=newNode;
			fun(newNode,++i);
		}
	}
	
	//頭插法建立單鏈表  棧形式先進後出
	public void afterInsert(Node node,int data){
		
		if(i<=10){
			Node newNode=new Node();//建立新的結點
			newNode.data=i;//設定資料域
			newNode.next=node.next;
			node.next=newNode;
			afterInsert(node,++i);
		}
		
	}
	

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		   Test test=new Test();
		   headNode=test.new Node();//頭指標
           //new Test6().fun(headNode,0);前插法
		   new Test().afterInsert(headNode,0);//後插法
           System.out.println("建立後的連結串列是:");//0 1 2 3 4 5 6 7 8 9 10
           while(headNode.next!=null){
        	   headNode=headNode.next;
        	   System.out.print(headNode.data+" ");
           }
	}

}