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

时间:2012-10-01 00:01:37

标签: java reverse singly-linked-list circular-list

我在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 个答案:

答案 0 :(得分:0)

a4.setNext(A1);

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