0

I write a list by C language. But it can not get the last number. The program accept some number when the number is not 0. And put number into a list. This is code:

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

The program returns 1 2 3 when I input 1 2 3 4 0. Could someone give me some advice? Thanks a lot!

changzhi
  • 2,641
  • 9
  • 36
  • 46

2 Answers2

1

Just check whether pHead is NULL instead of pHead->next. When you check pHead->next, you are exiting at the top of the loop without ever printing the last element.

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

}
merlin2011
  • 71,677
  • 44
  • 195
  • 329
1
p1 = p2 = (List *)malloc(sizeof(List));

p1 and p2 are pointing to same location.

This statement allocates memory for the List and assigns to p2 and the same value is assigned to p1

Allocate individually for both p1 and p2 p1 = malloc(sizeof(List)); p2 = malloc(sizeof(List));

Type cast is not required.

Sakthi Kumar
  • 3,047
  • 15
  • 28