用java实现了一个链表结构,键盘输入数字,将其依次加入链表,保证时刻升序排列。
数据结构通过定义一个类来实现,具体的代码如下:
import java.util.Scanner;
public class LinkedListConstructor {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
LinkedList ll = new LinkedList(0);
ll.setNext(null);// 初始化这个链表的头结点为0,next为null
while (sc.hasNextInt()) {
ll = addNewNode(ll, sc.nextInt());// 从表头开始遍历,找到插入的位置
}
System.out.println("Input finished!");
printLinkedList(ll);
sc.close();
}
private static void printLinkedList(LinkedList ll) {// 根据表头打印所有数据
while (ll != null) {
System.out.print(ll.getValue() + " ");
ll = ll.getNext();
}
}
private static LinkedList addNewNode(LinkedList ll, int n) {// 这个函数返回的是表头的位置
LinkedList header = ll;
LinkedList lnew = new LinkedList(n);// 先new一个节点
if (ll.getNext() == null) {
ll.setNext(lnew);
lnew.setNext(null);
} else {
while (ll.getNext()!=null&&ll.getNext().getValue() < n) {
ll = ll.getNext();
}
lnew.setNext(ll.getNext());
ll.setNext(lnew);
}
return header;
}
}
而其中LinkedList类定义为:
public class LinkedList {
private int value;
private LinkedList next;
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public LinkedList getNext() {
return next;
}
public void setNext(LinkedList next) {
this.next = next;
}
public LinkedList(int value) {
this.value = value;
}
public LinkedList() {
}
}
这个程序输入的时候需要注意一点,如果输入结束,可以随意输入一些非数字符号作为结束。否则算法不认为输入完成。。也可以用输入String类,再split,转成int值的方法。具体就不写了。