After breaking my head over this for quite sometime, I am looking for help. Maybe I am doing something really silly here. Below is a basic implementation of linkedlist. However, it does not seem to work. Can someone please take a look?
EDIT: By not working I mean its getting in to an endless loop in the else part of the add function.
#include <iostream>
struct node
{
int data;
node* link;
};
void add(struct node** list, int i)
{
//populate a node
node* tempNode = (node*) malloc(sizeof(node));
tempNode->data = i; //**This does not seem to initialize data**
tempNode->link = NULL; //**Same here**
//check if the list is empty
if(*list == NULL)
{
//create the node
*list = tempNode;
}
else
{
while((*list)->link != NULL); //Enters in to an endless loop here because the link is not initialized
(*list)->link = tempNode;
}
}
void print(node** list)
{
node* itr = *list;
while(itr != NULL)
{
std::cout << itr->data << "\n";
itr = itr->link;
}
}
int main()
{
node* linkedList = NULL;
node** t = &linkedList;
add(&linkedList, 10);
add(&linkedList, 20);
add(&linkedList, 30);
add(&linkedList, 40);
print(&linkedList);
}
Your
addfunction is wrong (theelsebranch). Since(*list)->linkdoesn’t get changed, it will loop forever. Try this.This inserts in
O(n); user786653 has a nice suggestion in the comments.