631 views
0 votes
0 votes

Why the following code is not giving desired results? The code simple push & appends the nodes in the linked list.

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

struct Node{
	int item;
	struct Node* next;
};

void push(struct Node** head,int item){
	struct Node* fresh = (struct Node*) malloc(sizeof(struct Node));
	fresh->item = item;
	fresh->next = *head;
	*head = fresh;
}

void append(struct Node** head,int item){
	struct Node* fresh = (struct Node*) malloc(sizeof(struct Node));
	fresh->item = item;
	struct Node** curr = head;
	while((*curr)->next!=NULL){
		*curr = (*curr)->next;
	}
	(*curr)->next = fresh;
	fresh->next = NULL;
}

void printList(struct Node* head){
	while(head!=NULL){
		printf("-> %d",head->item);
		head = head->next;
	}
}

int main(){
	struct Node *head = NULL;
	push(&head,5);
	push(&head,6);
	push(&head,7);
	append(&head,51);
	append(&head,53);
	printList(head);
	return 0;
}

Output desired : 7->6->5->51->53

Shown output : ->51->53

Where is the error in this code?

1 Answer

0 votes
0 votes

Hi

You are making a very small and unnoticed mistake. Observe this part of code--

void append(struct Node** head,int item){
	struct Node* fresh = (struct Node*) malloc(sizeof(struct Node));
	fresh->item = item;
	struct Node** curr = head;
	while((*curr)->next!=NULL){
		*curr = (*curr)->next;
	}
	(*curr)->next = fresh;
	fresh->next = NULL;
}

Look at the bold part. Head is a double pointer which keeps the address of starting node. Now here what you doing is you are passing the address of head node itself(node the node pointed by head) . This is the mistake you making, here you are giving the address of head node to curr variable. now curr variable can modify head address (Because this is call by reference). When you try to print your list you pass head address but head address is being updated by

*curr = (*curr)->next;

So head starts printing from where it is currently pointing.

So you can make a small change in your program for making it to work properly.

Try this 

void append(struct Node** head,int item){

struct Node* fresh = (struct Node*) malloc(sizeof(struct Node));

fresh->item = item;

struct Node* curr = *head;

while((curr)->next!=NULL){

curr = (curr)->next;

}

(curr)->next = fresh;

fresh->next = NULL;

}

i just removed one star and it is working correctly. 

Related questions

1 votes
1 votes
1 answer
1