【问题标题】:Print function messes up the linked list打印功能弄乱了链表
【发布时间】:2021-02-28 14:11:32
【问题描述】:
#include <stdio.h>
#include <stdlib.h>    
struct Node
{
    int val;
    struct Node *next;
};
struct List
{
    struct Node *head;
    struct Node *tail;
};
typedef struct List *List;

void Print(List temp)
{
    struct Node* print = temp->head;
    while(print->next!=NULL)
    {
        printf("%d  ", print->next->val);
        print->next = print->next->next;
    }
    printf("\n\n");
}

int main()
{
    int i;
    List Numbers;
    Numbers = (struct List *) malloc(sizeof(struct List));
    if (Numbers== NULL)
        printf("Out of memory!\n");
    Numbers->head = (struct Node *) malloc(sizeof(struct Node));
    if (Numbers->head == NULL)
        printf("Out of memory!\n");
    Numbers->head->next = NULL;
    Numbers->tail = Numbers->head;   

    printf("Enter 5 numbers:");
    struct Node* temp = Numbers->head;
    for(i=0;i<5;i++)
    {
        struct Node* newnode = (struct Node*)malloc(sizeof(struct Node));
        scanf("%d", &newnode->val);
        newnode->next = NULL;
        temp->next = newnode;
        temp = newnode;
        Numbers->tail = newnode;

    }
    Print(Numbers);
    Print(Numbers);    
    return 0;
}

当我第一次打印列表时,它会正确打印,但第二次它什么也不打印,程序崩溃。我不知道为什么列表会被破坏,即使我正在使用临时节点来打印它。我应该更改打印功能还是其他问题?

【问题讨论】:

  • 看起来您正在更改与print-&gt;next = print-&gt;next-&gt;next; 的链接太多指针:while(print != NULL) { printf("%d ", print-&gt;val); print = print-&gt;next;}

标签: c function linked-list


【解决方案1】:

你的问题出在这条线上:

print->next = print->next->next;

这一行改变了head-&gt;next的指针。当您第一次运行它时,head-&gt;next 的指针将更改为每个节点,最后设置为NULL。 要修复它,只需将其更改为:

print = print->next;

然后你就可以正确打印你的链表而不改变原来的链表了。

【讨论】:

    【解决方案2】:

    您可能想将print-&gt;next = print-&gt;next-&gt;next; 更改为print = print-&gt;next;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-11
      • 2016-10-23
      • 2020-01-16
      • 1970-01-01
      • 2020-12-12
      • 2017-03-01
      相关资源
      最近更新 更多