java学习第13天,链表

在实际应用中链表的使用非常普遍,应该用心领会,学习一下代码,弄明白意思

package java11to20;

public class D13_LinkedList {
	class Node {
		int data;
		Node next;

		public Node(int Value) {
			data = Value;
			next = null;
		}
	}

	Node header;

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		D13_LinkedList FirstList = new D13_LinkedList();
		System.out.println("初始化列表:" + FirstList.toLinkListStr());

		for (int i = 0; i < 10; i++) {
			FirstList.insert(0, i);
		}
		System.out.println("数据插入列表后: " + FirstList.toLinkListStr());
		FirstList.insert(11, 18);
		FirstList.delete(6);
		FirstList.delete(1);
		System.out.println("1.删除该位置数据后列表为:" + FirstList.toLinkListStr());
		System.out.println(String.format("数值5是在列表第%s位", FirstList.locate(5) + 1));
		FirstList.delete(0);
		System.out.println("2.删除该位置数据后列表为:" + FirstList.toLinkListStr());
		for (int i = 0; i < 7; i++) {
			FirstList.delete(0);
			System.out.println("第" + (i + 1) + "次删除后,列表值为:" + FirstList.toLinkListStr());
		}
	}

	public D13_LinkedList() {
		header = new Node(0);
	}

	public boolean insert(int Position, int Value) {
		Node node = header;
		Node newNode;
		for (int i = 0; i < Position; i++) {
			if (node.next == null) {
				System.out.println(String.format("第%s位置,插入数据非法", Position));
				return false;
			}
			node = node.next;
		}
		newNode = new Node(Value);
		newNode.next = node.next;
		node.next = newNode;
		return true;
	}

	public boolean delete(int Position) {
		if (header.next == null) {
			System.out.println("该列表为空。");
			return false;
		}
		Node node = header;
		for (int i = 0; i < Position; i++) {
			if (node.next.next == null) {
				System.out.println(String.format("位置%s非法", Position));
				return false;
			}
			node = node.next;
		}
		node.next = node.next.next;
		return true;
	}

	public void reset() {
		header.next = null;
	}

	public String toLinkListStr() {
		String result = "";

		if (header.next == null) {
			return "空列表";
		}
		Node node = header.next;
		while (node != null) {
			result += node.data + ", ";
			node = node.next;
		}
		return result;
	}

	public int locate(int Value) {
		int Position = -1;
		Node node = header.next;
		int CurrentPosition = 0;
		while (node != null) {
			if (node.data == Value) {
				Position = CurrentPosition;
				break;
			}

			node = node.next;
			CurrentPosition++;
		}
		return Position;
	}
}

输出结果:

初始化列表:空列表
数据插入列表后: 9, 8, 7, 6, 5, 4, 3, 2, 1, 0,11位置,插入数据非法
1.删除该位置数据后列表为:9, 7, 6, 5, 4, 2, 1, 0, 
数值5是在列表第42.删除该位置数据后列表为:7, 6, 5, 4, 2, 1, 0,1次删除后,列表值为:6, 5, 4, 2, 1, 0,2次删除后,列表值为:5, 4, 2, 1, 0,3次删除后,列表值为:4, 2, 1, 0,4次删除后,列表值为:2, 1, 0,5次删除后,列表值为:1, 0,6次删除后,列表值为:0,7次删除后,列表值为:空列表
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值