单链表之简单版

下面是个单链表,且无序的实现代码. 需要注意的是有个head节点, 该节点不存储数据,只是表示链表的头节点.

public class SingleLinkedListDemo {
    public static void main(String[] args) {
        //先创建几个节点
        Node node1 = new Node(1, "老子", "太上老君");
        Node node2 = new Node(2, "王达", "玉皇大帝");
        Node node3 = new Node(3, "萧炎", "炎帝");
        SingleLinkedList linkedList = new SingleLinkedList();
        linkedList.add(node1);
        linkedList.add(node2);
        linkedList.add(node3);
        linkedList.list();
    }
}

/**
 * 定义一个链表,用于管理每个Node节点
 */
class SingleLinkedList {
    // 初始化一个头节点, 不能动,用于去找链表的其它节点
    private Node head = new Node(0);

    //添加节点到单向链表尾部
    public void add(Node node) {
        // 1. 如何找到链表的尾节点
        Node temp = head;
        //遍历链表,找到最后的节点
        while (true) {
            if (temp.next == null) {
                break;
            }
            temp = temp.next;
        }
        // 当退出while循环时, temp指向了链表的最后
        temp.next = node;
    }

    public void list() {
        if (head.next == null) {
            System.out.println("链表为空");
            return;
        }

        Node temp = head.next;
        while (true) {
            // 判断是否到链表最后
            if (temp == null) {
                break;
            }
            // 打印
            System.out.println(temp);
            temp = temp.next;
        }

    }

}

class Node {
    int no;
    String name;
    String nickName;
    /**
     * 指向下一个节点
     */
    public Node next;

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

    public Node(int no, String name, String nickName) {
        this.no = no;
        this.name = name;
        this.nickName = nickName;
    }

    @Override
    public String toString() {
        return "Node{" +
                "no=" + no +
                ", name='" + name + '\'' +
                ", nickName='" + nickName +
                '}';
    }
}

 

 

注意Node节点中定义属性的权限问题, 使用的是默认权限,即同一个包中可用.  我们应该借鉴这种方式,不提供setter,getter方法,也不使用public等权限修饰符,一切似乎都恰到好处.

而且,jdk源码中大量使用此类模式. 所以应该没啥问题.

你可能感兴趣的:(单链表之简单版)