The data in the first node in my linked list keeps changing to the last node in the list. C language

Viewed 82

I am learning about C linked lists from the All In One C Desk Reference For Dummies.

Whenever I run the code, I seem to be able to add new elements alright, but when I display the contents, only the data in the last node is shown.

I have checked and rechecked the code, but as far as I can tell, I am writing it the same as the book. Thanks for the help!

As I don't know which part is the part that is wrong, I have supplied the full example from the book, except for subbing out the fflush() functions for my own code. Exercise 6.2.1 (Book 6 - Chapter 2 - The Bank Program - bank.c (if that helps))

/* Includes */
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<ctype.h>
#include"../../myheaders/myinput.h"

/* Function Protoyypes */
void addNewAccount(void);
void listAll(void);

/* Structures and global variables  */
struct account {
    int number;
    char lastname[15];
    char firstname[15];
    float balance;
    struct account *next;
};
struct account *firsta, *currenta, *newa;
int anum = 0;

/* Main program */
int main()
{
    char ch;
    firsta = NULL;

    do {
        puts("\nA - Add a new account");
        puts("L - List Accounts");
        puts("Q - Quit this program\n");
        printf("\tYour choice:");
        ch = getonlychar(&ch);
        ch = toupper(ch);
        switch (ch) {
            case 'A':
                puts("Add new account\n");
                addNewAccount();
                break;
            case 'L':
                puts("Listing accounts");
                listAll();
                break;
            case 'Q':
                puts("Quit\n");

            default:
                break;
        }
    } while (ch!= 'Q');

    return 0;
}

/* Definitions */
/* Add a new account */
void addNewAccount(void)
{
    newa = (struct account *)malloc(sizeof(struct account));
    
    /* Check to see if this is the first record.
     * If so, then initialize all the pointers to this
     * first structure in the database */
    if (firsta == NULL) {
        firsta = currenta = newa;
    }

    /* Otherwise, you must find the end of the structure list
     * easily spotted by the NULL pointer) and add on the
     * new structure you just allocated memorey for */
    else {
        currenta = firsta; /* Make first record current */
    }

    /* Loop through all records */
    while (currenta->next != NULL) {
        currenta = currenta->next;

        /* The last reord is found */
        currenta->next = newa; /* Save the address of new */
        currenta = newa; /* Make current record new */
    }

    /* Now you just fill in the new structure */
    anum++;
    printf("%27s: %5i\n", "Account number", anum);
    currenta->number = anum;
    printf("%27s: ", "Enter customer's last name");
    fgets(currenta->lastname, 14, stdin);
    printf("%27s: ", "Enter customer's first name");
    fgets(currenta->firstname, 14, stdin);
    printf("%27s: ", "Enter account balance");
    scanf(" %f", &currenta->balance);

    /* Finally, cap the new record with a NULL pointer
     * so that you know it's the last record */
    currenta->next = NULL;
}

void listAll(void)
{
    if (firsta == NULL) {
        printf("No records to show!\n");
    }
    else {
        printf("%6s %-15s %-15s %11s\n", "Acct#", "Last", "First", "Balance");
        currenta = firsta;
        do {
            printf("%6s %-15s %-15s %11s\n",
                    currenta->number,
                    currenta->lastname,
                    currenta->firstname,
                    currenta->balance);
        } while ((currenta = currenta->next) != NULL);
    }
    
}
2 Answers

I think your problem comes from this part of your code:

/* Loop through all records */
while (currenta->next != NULL) {
    currenta = currenta->next;

    /* The last reord is found */
    currenta->next = newa; /* Save the address of new */
    currenta = newa; /* Make current record new */
}

Maybe you want that:

/* Loop through all records */
while (currenta->next != NULL) {
    currenta = currenta->next;
}

/* The last reord is found */
currenta->next = newa; /* Save the address of new */
currenta = newa; /* Make current record new */

The point is that when you add a new item to the list, the new data replaces the previous items. It explains why you only see the last data.

Here is a simplified solution for your problem,

/* Includes */
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<ctype.h>

/* Function Protoyypes */
void addNewAccount(void);
void listAll(void);

/* Structures and global variables  */
struct account {
    int number;
    char lastname[15];
    char firstname[15];
    float balance;
    struct account *next;
};
struct account *firsta, *currenta, *newa;
int anum = 0;



/* Main program */
int main()
{
    char ch;
    firsta = NULL;
    while(ch!='Q'){
    
     puts("\nA - Add a new account");
        puts("L - List Accounts");
        puts("Q - Quit this program\n");
        printf("\tYour choice:");
        
        scanf(" %c", &ch);  
        
        ch = toupper(ch);
        switch (ch) {
            case 'A':
                puts("Add new account\n");
                addNewAccount();
                break;
            case 'L':
                puts("Listing accounts");
                listAll();
                break;
            case 'Q':
                puts("Quit\n");

            default:
                break;
        }
}
    return 0;
}


/* Definitions */
/* Add a new account */
void addNewAccount(void)
{
    newa = (struct account *)malloc(sizeof(struct account));
    /* Check to see if this is the first record.
     * If so, then initialize all the pointers to this
     * first structure in the database */
    if (firsta == NULL) {
        firsta = currenta = newa;
    }

    /* Otherwise, you must find the end of the structure list
     * easily spotted by the NULL pointer) and add on the
     * new structure you just allocated memorey for */
    else {
            
            currenta->next = newa; 
            currenta = currenta->next;
    }


    /* Now you just fill in the new structure */
    anum++;
    printf("%27s: %5i\n", "Account number", anum);
    currenta->number = anum;
    printf("%27s: ", "Enter customer's last name");
    fgets(currenta->lastname, 14, stdin);
    fgets(currenta->lastname, 14, stdin);
    printf("%27s: ", "Enter customer's first name");
    fgets(currenta->firstname, 14, stdin);
    printf("%27s: ", "Enter account balance");
    scanf(" %f", &currenta->balance);

    /* Finally, cap the new record with a NULL pointer
     * so that you know it's the last record */
    currenta->next = NULL;
}

void listAll(void)
{
    if (firsta == NULL) {
        printf("No records to show!\n");
    }
    else {
        printf("%6s %-15s %-15s %11s\n", "Acct#", "Last", "First", "Balance");
        currenta = firsta;
        

        
        while (currenta != NULL){
            printf("%d %s %s %f\n",
                    currenta->number,
                    currenta->lastname,
                    currenta->firstname,
                    currenta->balance);
            currenta=currenta->next;
        }
        

        

    }
    
}
Related