通过C程序打印列表无法打印最后一个数字

时间:2014-06-11 06:59:30

标签: c linux

我用C语言写一个列表。但它不能得到最后一个数字。当数字不是0时,程序会接受一些数字。并将数字放入列表中。这是代码:

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

typedef struct List{
    int data;
    struct List *next;
}List;

void initList(List **pList)
{
    *pList = NULL;
}

List *createList(List *pHead)
{
    List *p1, *p2;
    p1 = p2 = (List *)malloc(sizeof(List));
    if(p1 == NULL || p2 == NULL) {
            exit(0);
    }

    scanf("%d", &p1->data);
    p1->next = NULL;//create a node

    while(p1->data != 0) {
            if (pHead == NULL){
                    pHead = p1;
            }else{
                    p2->next = p1;
            }
            p2 = p1;
            p1 = (List *)malloc(sizeof(List));
            scanf("%d", &p1->data);
            p1->next = NULL;
    }
    return pHead;
}

void printList(List *pHead)
{
    if(pHead == NULL){
            printf("empty");
    }else{
            while(pHead->next != NULL){
                    printf("%d ", pHead->data);
                    pHead = pHead->next;
            }
    }

}

int main()
{
    List *pList = NULL;
    initList(&pList);
    pList = createList(pList);
        printList(pList);
    return 0;
}

当我输入1 2 3时,程序会返回1 2 3 4 0。有人可以给我一些建议吗?非常感谢!

2 个答案:

答案 0 :(得分:1)

只需检查pHeadNULL而不是pHead->next。当您检查pHead->next时,您将退出循环的顶部而不打印最后一个元素。

void printList(List *pHead)
{
    if(pHead == NULL){
        printf("empty");
    }else{
        while(pHead != NULL){
            printf("%d ", pHead->data);
            pHead = pHead->next;
        }
    }

}

答案 1 :(得分:1)

p1 = p2 = (List *)malloc(sizeof(List));

p1p2指向同一位置。

此语句为List分配内存并分配给p2,并将相同的值分配给p1

p1p2单独分配     p1 = malloc(sizeof(List));     p2 = malloc(sizeof(List));

不需要输入类型。

相关问题