Reputation: 195
I kept confusing by the bug of my code. I created a linked list and use the push()
to add elements and printList()
to output the elements, the code below works correctly.
#include <stdio.h>
#include <stdlib.h>
struct linkedList {
int _Value;
struct linkedList * _Next;
};
typedef struct linkedList linkedList_t;
/* Function to push a node */
void push( linkedList_t** listHead, int new_data )
{
/* allocate node */
linkedList_t* new_node =
(linkedList_t *) malloc( sizeof(linkedList_t) );
/* put in the data */
new_node->_Value = new_data;
/* link the old list off the new node */
new_node->_Next = *listHead;
/* move the head to point to the new node */
*listHead = new_node;
}
/* Function to print linked list */
void printList( linkedList_t *head )
{
linkedList_t *tmp = head;
while ( tmp != NULL )
{
printf( "%d ", tmp->_Value );
tmp = tmp->_Next;
}
}
int main( int argc, char* argv[] )
{
linkedList_t *head = NULL;
push( &head, 20 );
push( &head, 4 );
push( &head, 15 );
push( &head, 85 );
printList( head );
return 0;
}
The Problem is that when i change the arguments as single pointer like:
void push( linkedList_t* listHead, int new_data )
{
/* allocate node */
linkedList_t* new_node =
(linkedList_t *) malloc( sizeof(linkedList_t) );
/* put in the data */
new_node->_Value = new_data;
/* link the old list off the new node */
new_node->_Next = listHead;
/* move the head to point to the new node */
listHead = new_node;
}
when I called the printList()
function ,nothing happened , I think it was because head
kept equaling to NULL
but i could not find out what is wrong with my code,assuming head
will be changed when i call push()
in the main function
and my main function
is the following:
int main( int argc, char* argv[])
{
linkedList_t *head = NULL;
push( head, 20 );
push( head, 4 );
push( head, 15 );
push( head, 85 );
printList( head );
return 0;
}
I needed some suggestions .Anybody help? thanks!
Upvotes: 1
Views: 465
Reputation: 10733
You are actually passing the copy of head pointer when you use single pointer. In case of double pointer you are passing the address of head pointer so that changes to it makes sense.
You can make code working with single pointer version with minute change. In that case you need to return head pointer from your push function.
linkedList_t* push( linkedList_t* listHead, int new_data );
In that case change reflected would be:-
linkedList_t *head = NULL;
head = push( head, 20 );
head = push( head, 4 );
Hope I am clear enough...
Upvotes: 1