【问题标题】:One way linked list and unwanted first element afrter filling填充后的单向链表和不需要的第一个元素
【发布时间】:2014-02-17 17:57:13
【问题描述】:

我的单向链表有问题。它是用 C 语言编写的。

输入:

3

4 5 6

输出是

0 4 5 6

所以 0 是不需要的。我在做什么错,错误的通过名单?看起来在 Add() 函数中首先“如果”没有完成。但是为什么,因为传递列表是空的。

ideone link to code

这里有一些代码:

#include <stdio.h>
#include <stdlib.h>

typedef struct ELEMENT{
    int dane;
    struct ELEMENT *next;
}LIST;

void Add(LIST *FIRST, int x){
    LIST *ptr=FIRST,*el;

    el=(LIST*)malloc(sizeof(LIST));
    el->dane=x;
    el->next=NULL;

    if(ptr==NULL){
            ptr=el;
    }else{
        while(ptr->next!=NULL){
            ptr=ptr->next;
        }
        ptr->next=el;
    }
}

void Show(LIST *FIRST){
    LIST *ptr=FIRST;

    while(ptr!=NULL){
        printf("%d ",ptr->dane);
        ptr=ptr->next;
    }
    while(ptr!=NULL){
        ptr=ptr->next;
        free(ptr);
    }
}

LIST *HEAD=NULL;
int main()
{
    int i,counter,data;
    printf("Give me some data: \n");
    scanf("%d",&counter);

    for(i=0;i<counter;i++){
        scanf("%d",&data);
        Add(&HEAD,data);
    }

    printf("\nMy items:");
    Show(&HEAD);
    return 0;
}

【问题讨论】:

  • 注意:&amp;HEAD 类型为 LIST**
  • 在 Add() 或 GDB 中添加日志并跟踪它,看看有什么问题。

标签: c++ c data-structures linked-list structure


【解决方案1】:

例如修复

void Add(LIST **FIRST, int x){
    LIST *ptr=*FIRST,*el;

    el=(LIST*)malloc(sizeof(LIST));
    el->dane=x;
    el->next=NULL;

    if(ptr==NULL){
            *FIRST=el;
    }else{
        while(ptr->next!=NULL){
            ptr=ptr->next;
        }
        ptr->next=el;
    }
}

void Show(LIST *FIRST){
    LIST *ptr=FIRST;

    while(ptr!=NULL){
        printf("%d ",ptr->dane);
        ptr=ptr->next;
    }
    ptr=FIRST;
    while(ptr!=NULL){
        LIST *tmp = ptr;
        ptr=ptr->next;
        free(tmp);
    }
}

LIST *HEAD=NULL;
int main()
{
    int i,counter,data;
    printf("Give me some data: \n");
    scanf("%d",&counter);

    for(i=0;i<counter;i++){
        scanf("%d",&data);
        Add(&HEAD,data);
    }

    printf("\nMy items:");
    Show(HEAD);
    return 0;
}

【讨论】:

  • 现在我明白了我的错误以及它是如何工作的。谢谢。您的代码正在运行。
【解决方案2】:
if(ptr==NULL){
   ptr=el;
}

你在这里遇到了问题,在这种情况下,你只改变了 ptr,而 FIRST 保持不变,所以最终你什么都不做,只是返回后内存泄漏。

为了解决这个问题,你可以返回指针,或者按地址传递指针。

【讨论】:

    猜你喜欢
    • 2016-12-31
    • 2013-09-26
    • 2021-05-05
    • 2017-12-14
    • 1970-01-01
    • 2023-03-16
    • 1970-01-01
    • 2018-10-17
    • 1970-01-01
    相关资源
    最近更新 更多