zl程序教程

您现在的位置是:首页 >  后端

当前栏目

数据结构与算法--链表

2023-09-14 09:00:31 时间
首先链表分三种:
单链表,双链表,循环单链表

写个例子说明列表的创建和遍历:
public class LinkList {
    private Node head;

    private Node current;

    private void add(int data) {
        if(head == null) {
            head = new Node(data, null);
            current = head;
        } else {
            //创建新的结点
            Node node = new Node(data, null);
            //新创建的节点和列表进行关联
            current.next = node;
            //移动当前链表的索引位置
            current = node;
        }
    }

    private void print(Node node) {
        if(node == null) {
            return;
        }
        Node current = node;
        while(current != null) {
            System.out.println(current.data);
            current = current.next;
        }
    }

    /**
     * @ClassName: Node
     * @Description: TODO(定义Node数据类型)
     */
    classNode {
        int data;

        Node next;

        public Node() {
        }

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

    }

    public static void main(String[] args) {
        LinkList list = newLinkList();
        for(int i = 0; i < 10; i++) {
            list.add(i);
        }
        list.print(list.head);
    }

}
运行结果:
0
1
2
3
4
5
6
7
8
9