mike jackson
mike jackson

Reputation: 29

Print function messes up the linked list

#include <stdio.h>
#include <stdlib.h>    
struct Node
{
    int val;
    struct Node *next;
};
struct List
{
    struct Node *head;
    struct Node *tail;
};
typedef struct List *List;

void Print(List temp)
{
    struct Node* print = temp->head;
    while(print->next!=NULL)
    {
        printf("%d  ", print->next->val);
        print->next = print->next->next;
    }
    printf("\n\n");
}

int main()
{
    int i;
    List Numbers;
    Numbers = (struct List *) malloc(sizeof(struct List));
    if (Numbers== NULL)
        printf("Out of memory!\n");
    Numbers->head = (struct Node *) malloc(sizeof(struct Node));
    if (Numbers->head == NULL)
        printf("Out of memory!\n");
    Numbers->head->next = NULL;
    Numbers->tail = Numbers->head;   

    printf("Enter 5 numbers:");
    struct Node* temp = Numbers->head;
    for(i=0;i<5;i++)
    {
        struct Node* newnode = (struct Node*)malloc(sizeof(struct Node));
        scanf("%d", &newnode->val);
        newnode->next = NULL;
        temp->next = newnode;
        temp = newnode;
        Numbers->tail = newnode;

    }
    Print(Numbers);
    Print(Numbers);    
    return 0;
}

When I first print the list it prints out correctly but then the second time it prints nothing and program crashes. I dont know why the list is getting destroyed, even though I am using temp node to print it. Should I change the print function or the problem is something else ?

Upvotes: 0

Views: 38

Answers (2)

DipStax
DipStax

Reputation: 502

Your problem come from the line:

print->next = print->next->next;

This line change the pointer of head->next. When you run it the first time the pointer of head->next is changed to every node and at the end is set to NULL. To fix it just change it to:

print = print->next;

Then you can print you linked list correctly without changing the original linked list.

Upvotes: 2

TCvD
TCvD

Reputation: 622

You probably want to change print->next = print->next->next; to print = print->next;.

Upvotes: 1

Related Questions