反向单链表Java,检查是否循环

时间:2022-09-05 19:51:14

I implemented a singly linked list in Java. I can reverse a singly linked list and check whether a given list is circular. The interesting thing is I can reverse a circular list, too which is strange and interesting. Does it make sense to be able to reverse a circular list?Actually it should get reversed over and over again right? At the moment my below code is able to reverse a circular list and terminates. Is it correct?

我在Java中实现了一个单独的链表。我可以反转单个链接列表并检查给定列表是否为循环。有趣的是,我可以反转循环列表,这也很奇怪而且有趣。能够扭转循环列表是否有意义?实际上它应该一遍又一遍地反转对吗?目前,我的下面的代码能够反转循环列表并终止。这是对的吗?

public class ListNode{
    int value;
    ListNode next;  
    public ListNode(int value, ListNode next){
        this.value = value;
        this.next = next;
    }       
    public ListNode next(){
        return next;
    }
    public void setNext(ListNode next){
        this.next = next;
    }
    public int value(){
        return value;
    }
}

public class SinglyLinkedList {

    private ListNode head;

    public SinglyLinkedList(ListNode head){
        this.head = head;
    }

    public void reverse(){
        ListNode current = head;
        head = null;
        while (current!=null){
            ListNode temp = current;
            current = current.next;
            temp.next = head;
            head = temp;
        }
    }

    public static boolean isCircular(SinglyLinkedList list){
        ListNode counter1 = list.head;
        ListNode counter2 = list.head;
        while (counter1!=null && counter2!=null){
            counter1 = counter1.next;
            counter2 = counter2.next;
            if (counter2.next!=null){
                counter2 = counter2.next;
            } else 
                return false;
            if (counter1 == counter2)
                return true;
        }
        return false;
    }

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

    public static void main(String[] s){
        ListNode a4 = new ListNode(4, null);
        ListNode a3 = new ListNode(3, a4);
        ListNode a2 = new ListNode(2, a3);
        ListNode a1 = new ListNode(1, a2);
        a4.setNext(a1);

        SinglyLinkedList list1 = new SinglyLinkedList(a1);
        System.out.println(isCircular(list1));
        if (!isCircular(list1))
            printSinglyLinkedList(list1.head);
        list1.reverse();
        if (!isCircular(list1))
            printSinglyLinkedList(list1.head);




    }
}

1 个解决方案

#1


0  

a4.setNext(a1);

Remove the above statement. This makes it circular.

删除上述声明。这使它成为循环。

#1


0  

a4.setNext(a1);

Remove the above statement. This makes it circular.

删除上述声明。这使它成为循环。