【问题标题】:Checking if a linked List a Palindrome using a Node Class使用节点类检查链接列表是否为回文
【发布时间】:2016-10-25 19:05:26
【问题描述】:

我有一个项目问题,我需要检查一个链表是否是回文,向前和向后一样。我获得了一个名为 Node 类的课程,其中包含我不允许更改的特定信息,因此我必须使用我在该课程中拥有的内容并且不能在那里写更多内容来帮助我。我的问题是我可以通过列表,但我不知道如何倒退并比较值。

免责声明:我不想要一个完整的答案,只是提示/想法!

这是我无法更改且必须使用的课程:

class Node {
    /**
     *  The value stored in the node.
     */
    public Character value;

    /**
     *  A pointer to the next node in
     *  the list.
     */
    public Node next;

    /**
     *  A pointer to the previous node
     *  in the list. (Note: having this
     *  pointer makes this a "doubly linked"
     *  list.
     */
    public Node prev;

    /**
     *  A constructor to set up a
     *  node with a value.
     *  
     *  @param value the value to put in the node
     */
    public Node(Character value) {
        this.value = value;
    }

    /**
     *  A constructor to set up a
     *  node with a value and a pointer
     *  to the previous node (so I can
     *  append items easily in my test
     *  code).
     *  
     *  @param value the value to put in the node
     *  @param prev the previous node in the list
     */
    public Node(Character value, Node prev) {
        this.value = value;
        this.prev = prev;
    }

    /**
     *  Sets the next node in the list.
     *  
     *  @param n the next node in the list
     */
    public void setNext(Node n) {
        next = n;
    }

    /**
     *  Sets the previous node in the list.
     *  
     *  @param n the previous node in the list
     */
    public void setPrev(Node n) {
        prev = n;
    }
}

到目前为止,这就是我所拥有的,我只是尽我所能:

public static boolean listPalindrome(Node input) {

        if(input == null)
        {
            throw new IllegalArgumentException();
        }

        int count = 0;

        while(input.next != null)
        {
            count++;
        }

        Node holder = new Node(null, input.next);

        for(int i = 0;i<count;i++)
        {
            if(input.next != null)
            {
                break;
            }
            else
            {

            }
        }

        return false; //replace this
    }

请帮忙! 谢谢!

【问题讨论】:

标签: java


【解决方案1】:

count++ 有一个无限循环。 input.next 将始终为非空,因为您没有在循环中更新 input 的值。

如果您要克服这一点,则没有理由在您的代码中声明 new Node。假设链表的大小 > 0,您的循环也会在第一次迭代时中断,您应该检查 input.next == null,但将其放在循环的末尾。

另外请注意,您是 GMU 的学生,如果我为您提供更多帮助,那将是违反荣誉准则的;)

【讨论】:

  • 谢谢你,我只想要一个想法而不是答案,我不知道从哪里开始!
  • 我在帖子中修复了它,所以它是已知的。
猜你喜欢
  • 2017-12-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-21
  • 1970-01-01
相关资源
最近更新 更多