单链表

41 阅读1分钟

单链表

以下是代码的主要功能和结构:

  • public class Node {...}:定义了一个Node类,其中有两个属性:一个整型value和一个Node类型的next。还有一个构造函数Node(int value)
  • public static class SingleLinkListNode:定义了一个SingleLinkListNode内部静态类。
  • private Node head:单链表的头节点。
  • private Node tail:单链表的尾节点。
  • public void add(int value):是SingleLinkListNode类中的一个方法,用于向单链表中添加新的节点。
  • public void reverse():也是SingleLinkListNode类中的一个方法,用于反转整个单链表。
  • public void printNode():同样是SingleLinkListNode类中的一个方法,用于打印单链表中的所有节点。
  • public boolean cycle():是SingleLinkListNode类中的一个方法,用于判断单链表中是否存在环。
  • public static void main(String[] args):程序的主入口点,用于测试SingleLinkListNode类的功能。

main方法中,创建了SingleLinkListNode的实例node,向其中添加了三个元素,然后打印。接着调用了reverse方法,将单链表反转,再进行打印。

public class Node {


    private int value;

    private Node next;


    Node(int value) {
        this.value = value;
    }


    public static class SingleLinkListNode {

        private Node head;

        private Node tail;


        public void add(int value) {

            Node newNode = new Node(value);

            if (head == null) {
                head = newNode;
                tail = newNode;
            } else {
                tail.next = newNode;
                tail = newNode;

            }


        }


        public void reverse() {
            if (head == null) {
                return;
            }

            Node pre = null;
            Node next = null;
            while (head != null) {
                next = head.next;
                head.next = pre;
                pre = head;
                head = next;
            }
            head = pre;

        }

        public void printNode() {
            Node temp = head;
            while (temp != null) {
                System.out.print(temp.value + " ");
                temp = temp.next;
            }
            System.out.println();
        }


        public boolean cycle() {

            if (head == null || head.next == null) {
                return false;
            }
            Node slow = head;
            Node fast = head.next;
            while (fast !=slow) {
                if (fast==null||fast.next == null){
                    return false;
                }
                fast = fast.next.next;
                slow = slow.next;
            }
            return true;
        }

        public static void main(String[] args) {
            SingleLinkListNode node = new SingleLinkListNode();
            node.add(1);
            node.add(2);
            node.add(3);
            System.out.printf("反转之前:");
            node.printNode();
            node.reverse();
            System.out.printf("反转之后:");
            node.printNode();
        }

    }

}