package linearList;
public class Node {
public int no;
public String name;
public Node next; //指向下一个结点
//构造方法
public Node(int no,String name){
this.no = no;
this.name = name;
}
//重写toString方法
public String toString(){
return "Node [no=" + no +",name="+name + "]";
}
}
表类
package linearList;
public class SingleList {
//头结点
private Node head = new Node(0, "");
public void add(Node node){
Node temp = head;
while(true){
//temp.next = null,找到了链表的最后
if(temp.next == null){
break;
}else{
temp = temp.next;
}
}
//当退出while循环时,temp就指向了链表的最后
temp.next = node;
}
public void list(){
if(head.next == null){
System.out.println("链表为空");
return; //链表为空,直接退出
}
Node temp = head.next;
while(true){
//判断是否到链表最后
if(temp == null){
break;
}else{
System.out.println(temp.toString());
//打印出来之后,后移
temp = temp.next;
}
}
}
public static void main(String[] args) {
Node n1 = new Node(1, "宋江");
Node n2 = new Node(2, "卢俊义");
Node n3 = new Node(3, "吴用");
Node n4 = new Node(4, "林冲");
//加入单链表
SingleList s1 = new SingleList();
s1.add(n1);
s1.add(n2);
s1.add(n3);
s1.add(n4);
//显示
s1.list();
}
}