c++ - 单向链表和填充后不需要的第一个元素

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

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

对于输入:

3

4 5 6

输出是

0 4 5 6

所以 0 是不需要的。我做错了什么,错误的通过列表?看起来在 Add() 函数中第一个“if”没有完成。但是为什么,因为传递的列表是空的。

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;
}

最佳答案

例如修复

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;
}

关于c++ - 单向链表和填充后不需要的第一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21371652/

相关文章:

c++ - 弹出并插入堆栈

c++ - 读取文件中的 Eof 位

c++ - const_cast 的奇怪行为

c - 代码中这个以 ":"结尾的元素是什么意思?

c++ - 为什么 malloc(0) 的返回值是实现定义的?

C 未知类型名称 'my_structure'

c - Printf 忽略空值?

c - 有效地处理 c 中的文件

python - Python 中的列表或字典更快吗?

arrays - 包含 (0,L) 且条件 A[i] > A[R] 的数组总和