473,738 Members | 3,636 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

linked list implementation

hello,

I am writing a simple linked list implementation. When I use function
insert1 I must allocate to head in my main to get it to work otherwise
list stays empty but when I use function insert2 there is no need to
allocate to head this is the correct way.

why does this happen? why do we need to have a pointer to a pointer to
head in the insert function for this to work?

thank you

/*************** *************** *************** *************** ******/
int insert1(int n,NODE *head)
{
NODE *temp,*newnode;
newnode =(NODE*)malloc( sizeof(NODE));
if(newnode == NULL)
{
printf("\ncould not allocate node !!!");
return;
}
newnode->x = n;
newnode->next = NULL;
temp = head;
if(isEmpty(head ))
{ head = newnode;
printf("\nalloc ating to head!");
return; }
else
{ while(temp->next!=NULL && temp!=NULL)
temp = temp->next;
temp->next = newnode;
return newnode->x; }
}

this requires the following in main
NODE *head;
head = (NODE*)malloc(s izeof(NODE));
insert1(4,head) ;
/*************** *************** *************** *************** **********/

int insert2(int n,NODE **head)
{
NODE *temp,*newnode;
newnode =(NODE*)malloc( sizeof(NODE));
if(newnode == NULL)
{
printf("\ncould not allocate node !!!");
return;
}
newnode->x = n;
newnode->next = NULL;
temp = *head;
if(isEmpty(*hea d))
{ *head = newnode;
printf("\nalloc ating to head!");
return; }
else
{ while(temp->next!=NULL && temp!=NULL)
temp = temp->next;
temp->next = newnode;
return newnode->x; }
}

this requires the following in main
NODE *head;
head = NULL;
insert(4,&head) ;

Nov 14 '05 #1
8 1696

fa*****@serviho o.com wrote:
hello,

I am writing a simple linked list implementation. When I use function
insert1 I must allocate to head in my main to get it to work otherwise list stays empty but when I use function insert2 there is no need to
allocate to head this is the correct way.

why does this happen? why do we need to have a pointer to a pointer to head in the insert function for this to work?

thank you

/*************** *************** *************** *************** ******/
int insert1(int n,NODE *head)
{
NODE *temp,*newnode;
newnode =(NODE*)malloc( sizeof(NODE));
[clip]
if(isEmpty(head ))
{ head = newnode;
printf("\nalloc ating to head!");
return; }
[clip]
int insert2(int n,NODE **head)
{
NODE *temp,*newnode;
newnode =(NODE*)malloc( sizeof(NODE));
[clip]
if(isEmpty(*hea d))
{ *head = newnode;
printf("\nalloc ating to head!");
return; }


Think of the following code:

void foo(int x) { //local x == 0
x = 10; //local x == 10
} //local x ceases existing

int main(void) {
int x = 0;
foo(x);

printf("%i", x);
}

What will be printed, 0 or 10?

void foo(NODE* x) { //local x == NULL
x = 10; //local x == 10
} //local x ceases to exist

int main(void) {
NODE* x = NULL;
foo(x);

printf("%i", (int)x);
}

So what you have to do is make sure that the local version of head
isn't just a copy of the true head, but instead is a copy of the
_location_ of the real head so that you can effect it.

* I would also note that your insert functions are supposed to return
int, yet you aren't returning anything. If your compiler isn't
erroring, you might want a better one.

-Chris

Nov 14 '05 #2
fa*****@serviho o.com wrote:
I am writing a simple linked list implementation. When I use function
insert1 I must allocate to head in my main to get it to work otherwise
list stays empty but when I use function insert2 there is no need to
allocate to head this is the correct way.

why does this happen? why do we need to have a pointer to a pointer to
head in the insert function for this to work?


Does <http://www.eskimo.com/~scs/C-faq/q4.8.html> help?

Richard
Nov 14 '05 #3
fa*****@serviho o.com wrote:
hello,

I am writing a simple linked list implementation. When I use function
insert1 I must allocate to head in my main to get it to work otherwise
list stays empty but when I use function insert2 there is no need to
allocate to head this is the correct way.

why does this happen? why do we need to have a pointer to a pointer to
head in the insert function for this to work?

thank you

/*************** *************** *************** *************** ******/
int insert1(int n,NODE *head)
{
NODE *temp,*newnode;
newnode =(NODE*)malloc( sizeof(NODE));
if(newnode == NULL)
{
printf("\ncould not allocate node !!!");
return;
}
newnode->x = n;
newnode->next = NULL;
temp = head;
if(isEmpty(head ))
{ head = newnode;
printf("\nalloc ating to head!");
return; }
else
{ while(temp->next!=NULL && temp!=NULL)
temp = temp->next;
temp->next = newnode;
return newnode->x; }
}

this requires the following in main
NODE *head;
head = (NODE*)malloc(s izeof(NODE));
insert1(4,head );
/*************** *************** *************** *************** **********/

int insert2(int n,NODE **head)
{
NODE *temp,*newnode;
newnode =(NODE*)malloc( sizeof(NODE));
if(newnode == NULL)
{
printf("\ncould not allocate node !!!");
return;
}
newnode->x = n;
newnode->next = NULL;
temp = *head;
if(isEmpty(*hea d))
{ *head = newnode;
printf("\nalloc ating to head!");
return; }
else
{ while(temp->next!=NULL && temp!=NULL)
temp = temp->next;
temp->next = newnode;
return newnode->x; }
}

this requires the following in main
NODE *head;
head = NULL;
insert(4,&head );

Yes, the prototype you describe with function insert2 is the way to do
it. However, the
function definition is flawed. First, you are returning a value from the
function. Make it
a meaningful one that can signal the success or failure of the insert.
Also, as you seek
the tail of the list your code has a flaw in which an attempt to
dereference a NULL value
may occur. See a corrected solution below.

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

typedef struct NODE
{
int x;
struct NODE *next;
} NODE;

int Insert2NODE(int n,NODE **head); /* Insert at tail */
int Insert1NODE(int n,NODE **head); /* Insert at head */
void PrintNODE(const NODE *p); /* Print the list */
void FreeNODE(NODE **p); /* Free the list */

int main(void)
{
NODE *head = NULL;

puts("Inserting at tail of list");
Insert2NODE(22, &head);
Insert2NODE(33, &head);
Insert2NODE(44, &head);
PrintNODE(head) ;
FreeNODE(&head) ;

puts("\nInserti ng at head of list");
Insert1NODE(22, &head);
Insert1NODE(33, &head);
Insert1NODE(44, &head);
PrintNODE(head) ;
FreeNODE(&head) ;
return 0;
}

int Insert2NODE(int n,NODE **head)
{ /* Insert new node at tail of list */
NODE **temp,*newnode ;
newnode =malloc(sizeof *newnode);
if(newnode != NULL)
{
newnode->x = n;
newnode->next = NULL;
/* Seek end of linked list */
for(temp = head;*temp;temp = &(*temp)->next) ;
*temp = newnode;
return 1; /* Success */
}
return 0; /* Failure */
}

void PrintNODE(const NODE *p)
{
for( ;p; p = p->next)
printf("x = %d\n",p->x);
return;
}

void FreeNODE(NODE **p)
{
NODE *tmp;

for( ; *p; *p = tmp)
{
tmp = (*p)->next;
free(*p);
}
return;
}

int Insert1NODE(int n,NODE **head)
{ /* Place new node at head of linked list */
NODE *newnode;

newnode =malloc(sizeof *newnode);
if(newnode != NULL)
{
newnode->x = n;
newnode->next = *head;
*head = newnode;
return 1; /* Success */
}
return 0; /* Failure */
}

Nov 14 '05 #4
Thank you very much gentlemen you have been of immense help. However, I
still have two queries.

1) I can see the point Chris is making that insert1 modifies a local
variable, however is that not a problem solved by a single pointer as
in if we do

/*************** *************** *************** *************** ****/
void foo1(int *x) { //local x == 0
x = 10; //local x == 10

} //local x ceases existing

int main(void) {
int *x = 0;
printf("before foo x = %i",*x);

foo(x);

printf("\nafter %i", x);

}
/*************** *************** *************** *************** ********/

this will print
before foo x = 0;
after 10;

so it works with single pointer reference the question is why then
should i do
/*************** *************** *************** *************** *****88/
void foo2(int **x) { //local x == 0
**x = 10; //local x == 10

} //local x ceases existing

int main(void) {
int *x;
*x = 0;
printf("before foo x = %i",*x);

foo(&x);

printf("\nafter %i", *x);

}

prints
before foo x= 0
after 10
/*************** *************** *************** *************** *****/
in this foo case foo1 matches insert1 while foo2 matches insert2. In
the case of foo the results are the same in the case of insert they are
not why?

2) enlighten me if you will sir on the meaning of
for(temp = head;*temp;temp = &(*temp)->next) ;
and "flaw in which an attempt to dereference a NULL value may occur".
what is the flaw where is it located and what can i do to fix it.

thank you very much.

Nov 14 '05 #5
fa*****@serviho o.com wrote:


void foo1(int *x) { //local x == 0
x = 10; //local x == 10
Since x is a pointer, assigning an integer value to it is a diagnosable
error.

} //local x ceases existing

int main(void) {
int *x = 0;
Equivalent to int *x = NULL;
printf("before foo x = %i",*x);
Undefined behaviour. x doesn't currently point to an int object,
so dereferencing it is incorrect.
this will print
before foo x = 0;
after 10;


Actually, it could print "bananas". The behaviour is undefined.

(Similar problems with second code fragment.)
Nov 14 '05 #6
Richard Bos wrote:
fa*****@serviho o.com wrote:
I am writing a simple linked list implementation. When I use
function insert1 I must allocate to head in my main to get it to
work otherwise list stays empty but when I use function insert2
there is no need to allocate to head this is the correct way.

why does this happen? why do we need to have a pointer to a
pointer to head in the insert function for this to work?


Does <http://www.eskimo.com/~scs/C-faq/q4.8.html> help?


However he doesn't really need that. The following technique works
to insert items at the head of a list. The list can easily be
reversed later if desired.

struct node {
struct node *next;
whatever datum;
}

struct node *insert(struct node *root, whatever data)
{
struct node *new;

if (!(new = malloc(sizeof(* new)))) {
/* memory exhaustion error handling */
new = root; /* avoid losing existing list */
}
else {
/* assign data to new->datum */
/* may involve strcpy etc. */
new->next = root;
}
return new;
}

and the usage will be somewhere as:

struct node *root = NULL;

....
root = insert(root, newdata);

--
"If you want to post a followup via groups.google.c om, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers." - Keith Thompson
Nov 14 '05 #7
fa*****@serviho o.com wrote:
Thank you very much gentlemen you have been of immense help. However, I
still have two queries.


In regrads to querie 2:
2) enlighten me if you will sir on the meaning of
for(temp = head;*temp;temp = &(*temp)->next) ;
and "flaw in which an attempt to dereference a NULL value may occur".
what is the flaw where is it located and what can i do to fix it.

The definition as posted:

int insert2(int n,NODE **head)
{
NODE *temp,*newnode;
newnode =(NODE*)malloc( sizeof(NODE));
if(newnode == NULL)
{
printf("\ncould not allocate node !!!");
return;
}
newnode->x = n;
newnode->next = NULL;
temp = *head;
if(isEmpty(*hea d))
{ *head = newnode;
printf("\nalloc ating to head!");
return; }
else
{ while(temp->next!=NULL && temp!=NULL)
temp = temp->next;
temp->next = newnode;
return newnode->x; }
}

Assuming that function isEmpty will identify a condition where *head
is NULL
then it appears that the else clause will work in reaching the end of
the list.
So, I misled you on the dereference of a NULL value in the function
definition.
However, you will need to correct the returns and make it more meaningful.

The loop:

for(temp = head;*temp;temp = &(*temp)->next) ;
where temp is type NODE **
is another way of seeking the end of the loop.

Nov 14 '05 #8
What is the difference by using *head, where we just put on pointer to
the head pointer rather than what you have been implemention, Putting
**head

What differnce did that make and what is the use .. as in your code.

int Insert2NODE(int n,NODE **head);

Thank you.

Regards,
Billy

Nov 14 '05 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
11875
by: George M Jempty | last post by:
Is there a good linked list implementation in the public domain? Or that someone on this group has already written that they'd like to put in the public domain, right here on this newsgroup? I've googled and been disappointed. TIA George
5
2327
by: Darryl B | last post by:
I can not get anywhere on this project I'm tryin to do. I'm not expecting any major help with this but any would be appreciated. The assignment is attached. The problem I'm having is trying to set up the class link and tel_list. I set up a class person with strings for name, town, and number. I just don't know how to set up the classes w/ their methods (constructors and operations). I'm stuck on the assignment operator and the add and...
12
15097
by: Eugen J. Sobchenko | last post by:
Hi! I'm writing function which swaps two arbitrary elements of double-linked list. References to the next element of list must be unique or NULL (even during swap procedure), the same condition should be kept for references to previous element of list. Here is my solution below: struct node {
13
2190
by: XXXXXX.working.in.my.blood | last post by:
hi all, i need help with linked lists... the problem is this, "reverse the contents of a singly linked list without using a temporary node"... solution with code will be appreciated...
4
4284
by: FBM | last post by:
Hi, I am working on a program that simulates one of the elements of ATM. The simulation stores events which occurs every some milliseconds for a certain amount of time. Every time that an event is stored in a double linked list, the whole list is sorted for the next round. My problem appears when subjecting the program to heavy load, that is, when I run the simulation for more than 10,000 miliseconds (every event occurs in...
6
5327
by: Fazana | last post by:
I was doing one of the question but my program was not working properly. Can anyone help me with it pliz........ Here is the question for the program Question. Part 1. Add the function splitAt to split a linked list at a node whose Data is given. Suppose you have a list with the elements
51
8644
by: Joerg Schoen | last post by:
Hi folks! Everyone knows how to sort arrays (e. g. quicksort, heapsort etc.) For linked lists, mergesort is the typical choice. While I was looking for a optimized implementation of mergesort for linked lists, I couldn't find one. I read something about Mcilroy's "Optimistic Merge Sort" and studied some implementation, but they were for arrays. Does anybody know if Mcilroys optimization is applicable to truly linked lists at all?
9
2843
by: william | last post by:
When implementing Linked list, stack, or trees, we always use pointers to 'link' the nodes. And every node is always defined as: struct node { type data; //data this node contains ... node * nPtr; //the next node's pointer }
8
2728
by: Jeff Bown | last post by:
Consider implementing a (doubly) linked list. The simplest strategy is to provide functions item_t add_item(item_t predecessor); void delete_item(item_t item); where add_item allocates memory for a new list item and returns it (or NULL), and delete_item frees that memory. However, if at startup the program immediately adds a large number of items to a list, then all those calls to malloc() become expensive.
0
8969
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9476
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9335
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9263
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8210
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
4825
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3279
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2745
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2193
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.