单链表的创建和遍历

单链表的创建和遍历


public class LinkList3 {

	public Node head;
	public Node current;//成员变量 current 方便添加和遍历的操作,用来表示当前节点的索引

	public static void main(String[] args) {
		LinkList3 list = new LinkList3();
		// 向LinkList中添加数据
		for (int i = 0; i < 10; i++) {
			list.add(i);
		}

		list.print(list.head);// 从head节点开始遍历输出
	}

	// 方法:向链表中添加数据
	public void add(int data) {
		// 判断链表为空的时候
		if (head == null) {// 如果头结点为空,说明这个链表还没有创建,那就把新的结点赋给头结点
			head = new Node(data);
			current = head;
		} else {
			// 创建新的结点,放在当前节点的后面(把新的结点和链表进行关联)
			current.next = new Node(data);
			// 把链表的当前索引向后移动一位
			current = current.next; // 此步操作完成之后,current结点指向新添加的那个结点
		}
	}

	// 方法:遍历链表(打印输出链表。方法的参数表示从节点node开始进行遍历
	public void print(Node node) {
		if (node == null) {
			return;
		}

		current = node;
		while (current != null) {
			System.out.println(current.data);
			current = current.next;
		}
	}

    /*
    节点类Node是内部类;使用内部类的最大好处是可以和外部类进行私有操作的互相访问。
    内部类访问的特点是:内部类可以直接访问外部类的成员,包括私有;外部类要访问内部类的成员,必须先创建对象。
    */
	class Node {
		// 注:此处的两个成员变量权限不能为private,因为private的权限是仅对本类访问。
		int data; // 数据域
		Node next;// 指针域

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值