java创建链表

2020-10-28 14:34:03 浏览数 (1)

代码语言:javascript复制
package number;
public class chapter02 {
	public static void main(String[] args) {
		//生成5个节点
		Node Head = new Node(0,null); //产生头节点
		Node End = new Node(0,null);  //产生尾节点
		for(int i = 0;i<5;i  ){
			//创建节点
			Node body = new Node();
			Head.setSum(i 1);
			if(Head.next==null){
				//只有头结点
				Head.next = body;
			}else{
				End.next = body;
			}
			body.setData(i, null);
			End = body;
		}
		while(Head!=null){
			Head.getData();
			Head = Head.next;
		}
	}
}
//定义链表
 class Node{
	private int data; //节点数据
	public Node next; //下一个节点
	public Node(){}
	public Node(int data,Node next){
		this.data = data;
		this.next = next;	
	}
	public int isNull(){
		return this.data;
	}
	public void setData(int data,Node next){
		this.data = data;
		this.next = next;
	}
	public void setSum(int Sum){
		this.data = Sum;
	}
	public void getData(){
		System.out.println(this.data);
	}
}

0 人点赞