zoukankan      html  css  js  c++  java
  • 4.单链表的创建和建立

    public class LinkList {
        public Node head;
        public Node current;
    //向链表中添加数据
        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;
            }
        }
    
        class Node {
            //注:此处的两个成员变量权限不能为private,因为private的权限是仅对本类访问
            int data;//数据域 
            Node next;//指针域
            public Node(int data) {
                this.data = data;
            }
        }
    
        public static void main(String[] args) {
            LinkList list = new LinkList();
            //向LinkList中添加数据
            for (int i = 0; i < 10; i++) {
                list.add(i);
            }
            list.print(list.head);// 从head节点开始遍历输出
        }
    }

    运行结果:

    0
    1
    2
    3
    4
    5
    6
    7
    8
    9

    上方代码中,这里面的Node节点采用的是内部类来表示。使用内部类的最大好处是可以和外部类进行私有操作的互相访问。

     注:内部类访问的特点是:内部类可以直接访问外部类的成员,包括私有;外部类要访问内部类的成员,必须先创建对象。

     为了方便添加和遍历的操作,在LinkList类中添加一个成员变量current,用来表示当前节点的索引。

    这里面的遍历链表的方法中,参数node表示从node节点开始遍历,不一定要从head节点遍历。

  • 相关阅读:
    word-wrap与word-break为长单词换行
    background-origin与background-clip的“区别”
    box-shadow
    你不知道的border-radius
    当document.write 遇到外联script
    getAttribute()方法的第二个参数
    Backbone.js入门教程第二版笔记(3)
    Backbone.js入门教程第二版笔记(2)
    php中的字符串常用函数(二) substr() 截取字符串
    php中类和对象的操作
  • 原文地址:https://www.cnblogs.com/guweiwei/p/6845967.html
Copyright © 2011-2022 走看看