链表专题之一:创建链表,打印链表

package offer.linklist;

public class LinkList {
	// 头结点
	public Node head;
	// 当前结点
	public Node current;

	// 添加结点
	public void add(int data) {
		// 判断链表是否为null
		if (head == null) {
			// 链表为null,则表示链表中还没有结点
			// 头结点为新加入结点
			head = new Node(data);
			// 当前的结点变为头结点
			current = head;
		} else {
			// 链表不为null,则当前结点的下一个结点为新加入结点
			current.next = new Node(data);
			// 当前的结点变为新加入的结点
			current = current.next;// 这一步是关键,别忘!!!!
		}
	}

	// 定义内部类-Node
	class Node {
		public int data;
		public Node next;

		public Node(int data) {
			this.data = data;
		}
	}

	// 打印链表
	public void printLinkList(LinkList list) {
		Node current = list.head;
		while (current != null) {
			System.out.print("--->" + current.data);
			current = current.next;
		}
	}

	// 测试链表
	public static void main(String[] args) {
		LinkList list = new LinkList();
		for (int i = 0; i < 5; i++) {
			list.add(i);
		}
		list.printLinkList(list);
	}
}


转载于:https://my.oschina.net/u/2477353/blog/649912

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值