java数据结构之从链表

用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值的方法。具体就不写了。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值