1. 程式人生 > >java簡單鏈表實現

java簡單鏈表實現

package testjar;

public class Node {
	private int val;
	private Node next;

	public Node() {
		// TODO Auto-generated constructor stub
		next=null;
	}
	public Node(int val) {
		// TODO Auto-generated constructor stub
		this.val=val;
		next=null;
	}
	public int getVal() {
		return val;
	}
	public void setNext(Node next) {
		this.next=next;
	}
	public Node getNext() {
		return next;
	}
}


以上程式碼為節點程式碼,建構函式要把下個節點指向位置置為空

package testjar;


public class e {

	public e() {
		// TODO Auto-generated constructor stub
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int[] data={1,2,3,4,5,6,7,8,9,10};
		Node p;
		Node head=new Node();
		p=head;
		for(int i=0;i<data.length;i++){
			p.setNext(new Node(data[i]));
			p=p.getNext();
		}
		p=head.getNext();
		for(int i=0;i<data.length;i++){
			System.out.println(p.getVal());
			p=p.getNext();
		}
		
	}
}


用資料生成連結串列,熱後再分別打印出來