【问题标题】:Reverse Singly Linked List Java, check whether circular反向单链表Java,检查是否循环
【发布时间】:2012-09-21 21:11:56
【问题描述】:

我在 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);




    }
}

【问题讨论】:

  • 鉴于您对reverse 的实现,循环列表是可逆的似乎很奇怪,作为您的停止条件,current 最终是null,不应该在循环列表中命中。
  • @MarkElliot 如您所见, list1 是循环的,但同时是可逆的。我的第一个问题是能够反转循环单链表是否有意义?在我看来,从理解的角度来看,有两个不同的方向来浏览列表是有意义的。我的想法对吗?
  • 我也遇到了这个问题。能够反转一个循环列表并不奇怪,实际上搜索方向在找到或不找到方面是无关紧要的,这是标识循环列表的属性之一。
  • @Bob 只有订购了商品才有意义。
  • @Bob,我有兴趣看到带有循环的反向列表的一些输出,我想您的头节点将保持不变,并且循环开始之前的任何路径也将最终保持不变,但循环本身会翻转,现在我想通了......

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


【解决方案1】:

a4.setNext(a1);

删除上面的语句。这使它成为圆形。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-09-02
    • 1970-01-01
    • 2016-06-07
    • 1970-01-01
    • 2021-07-05
    • 2016-09-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多