0

我有一个关于创建Circular Linked List没有添加方法的单曲的问题。只是 Node 的一个内部类,然后是一个带有toString方法的外部构造函数。
我很难returningList,我一直没有回报。我不知道为什么,因为我无法实现 add 方法。我必须在我的构造函数中创建一个循环链接列表,以便让我对它有一些了解。但是我如何将值分配给我Nodesheadtail

class Number{ 

class Node
{
        public int num=0;           // node's position in line
        public Node next=null;  // Reference to next node
        /**
        * Node constructor, initializes number
        */

        public Node(int number)
        {
               //
            num = number;
            next = null;
        }

        public String toString() {
            return "" + num;
        }

}

private int number;
private Node head = null;   // Linked list of prisoners
private Node tail = null;   // Tracks end of list as it is constructed

/**
 * constructs a circular linked list of
 * @param n Nodes, current is the first Node and tail is the last Node (next of tail is current)
 */

public Number(int n)
{
    //
    number = n;
    LinkedList numb1 = new LinkedList();
    for (int i = 1; i <= number; i++) {
        numb1.add(i) //head I will have 1, 2, 3... n
    }
    head = null; //how would I make this reference head?
    tail = null; //how would I make this reference tail?
 }

/*
 * prints all Numbers starting from head until tail
 */
@Override
 public String toString()
 {
//
     String strVal = "";
     for (Node current = head; current != null; current = head.next) {
         strVal = strVal + current.num;
     }
     return strVal;
 }

我认为原因在于 for loop
通过拥有current != null,它会继续运行,因为 current 永远不能为空,因为它无休止地引用,因为它是一个循环链接列表。但是,它至少会返回一些东西,而不是什么都没有。

说我打电话 Number newNum = new Number(6);
System.out.println(newNum);
我应该出局
1 2 3 4 5 6

4

2 回答 2

1

使用这个数据结构

class CList {

 int size;
 CNode head;

class CNode {
 int data;
 CNode next; 

}

}

在 CList 的构造函数中初始化为head0 。nullsize

于 2013-11-21T06:33:29.953 回答
0
  1. 首先你需要修复 Number 构造函数。您应该将头分配给第一个节点,将尾分配给最后一个节点
 public Number(int n) {
        number = n;
        head = new Node(0);
        Node prev = head;
        for (int i = 1; i <=number; i++) {
            Node node = new Node(i);
            prev.next=node; // head I will have 1, 2, 3... n
            prev=node;
        }
        tail=prev;
    }

2. 在 toString 方法中,您总是引用 head.next 导致无限循环,因为您从未命中 null (当前!= null 永远不会在您的代码中变为真)

 public String toString() {
        String strVal = "";
        for (Node current = head; current != null; current = current.next) {
            strVal = strVal +" "+ current.num;
        }
        return strVal;
    }

编辑:我想补充的一件事是,您的实现是普通链表而不是循环链表。要使其循环,您应该将尾指向头,tail=head

于 2013-11-21T07:14:57.817 回答