打印链接列表无限循环C.

时间:2016-12-01 21:56:48

标签: c linked-list

我正在尝试在添加节点后打印链接列表。我有一个虚拟节点来启动列表

Object.prototype

但是当我打印时,我得到一个无限循环打印出新添加节点的数据字段。关联列表可怕......我做错了什么?

4 个答案:

答案 0 :(得分:1)

这是因为在此之后:

while (!tmp->next) {
    tmp->next = newNode;    /* inserts new node into array */
    tmp = newNode;      /* points head to newly added node */
}

head指向newNode和newNode-> next指向newNode。

这就是问题所在。 实际上插入newNode是一个问题。你将不得不改变它。

答案 1 :(得分:1)

我假设您正在尝试将新节点添加到阵列的末尾(也就是推送)。 所以试试这个:

    Socket socket = null;
    InetSocketAddress addr = new InetSocketAddress(host, port);
    Proxy proxy = new Proxy(Proxy.Type.HTTP, addr);
    try
        {
            socket = new Socket(proxy);
            socket.connect(addr, getUrlConnectTimeout());
        }
     catch (IOException ioe)
       {
        logger.info("IOE");
        }

答案 2 :(得分:1)

while (tmp->next) {
   tmp->next = newNode;    /* inserts new node into array */
   tmp = newNode;      /* points head to newly added node */
}

在这个片段中,你失去了对下一个节点的参考,只是在头部附近添加了newNode。例如,您有以下列表:

[1]->[2]->[3]

你想把一个新元素推入该列表:[4],执行推送功能时会发生什么(上面的代码片段):

tmp = head; // tmp = [1]
while(tmp->next) {
    tmp->next = newNode; // [1]->next = [4]
    tmp = newNode; // tmp = [4]
}

因此,下次'(tmp-> gt; next)'被评估时,它将被评估为:[4] - > next并且它将为NULL,从而打破循环。您的列表将是:

[1]->[4]

其他元素丢失,因为您没有指向它们的引用,这称为内存泄漏,因为您以后无法释放它们。

你可以用这种方式编写推送功能:

tmp = head;
while(tmp->next)
    tmp = tmp->next;
tmp->next = newNode // Adds new node to the tail of the linked list

答案 3 :(得分:1)

您通过以下行创建了一个封闭的圆圈链接列表:

while (!tmp->next) {
    tmp->next = newNode;    /* inserts new node into array */
    tmp = newNode;          /* points head to newly added node */
}

所以在这之后实际上你得到newNode->next = newNode这是`tmp-> next = tmp。

所以不应该这样做,你应该这样做:

while (tmp->next) {
    tmp = tmp->next;    //Find the last node
}
tmp->next = newNode;    //Inserts new node into the end of the array
相关问题