Hey guys, I'm needing some help with inserting into a linked list.
I'm trying to do it with the function I have created (see bottom of provided code), at first, I thought it worked fine, because after inserting, I can run my display() function, and it looks as if a new node has been added. However, upon closer inspection I realized that things were getting reaaally screwy, as I kept getting Segmentation Faults when I used my find function after inserting.
To be honest... I have no idea why this won't work.. although I'm guessing its because the node I'm creating inside my function is only local to the function???
I've been cruising the internets for a while now.. and it seems as if theres an easier way to insert if you have a "createnode()" function... but when I tried to implement that technique I just dug my hole deeper.
Help would be appreciated beyond belief.
Code:
#include <stdio.h>
typedef struct LinkedList NODE;
struct LinkedList{
int info;
NODE *next;
};
int main()
{
int val;
NODE first;
first.info = 1;
NODE second;
second.info = 2;
NODE third;
third.info = 3;
NODE fourth;
fourth.info = 4;
fourth.next = NULL;
first.next = &second;
second.next = &third;
third.next = &fourth;
NODE *top;
top = &first;
display(top);
insert(top, &third, &val);
display(top);
return(0);
}
/*~~~~~~~~DISPLAY ELEMENTS~~~~~~~~~~~*/
display(NODE *p)
{
printf("%d %d\n", (*p).info, *p);
if(p->next == NULL)
{printf("KABLOOOOIE\n\n");
return;}
display((*p).next);
}
/*~~~~~~~~~SEARCH ELEMENT~~~~~~~~~~*/
search(NODE *p, int srch)
{
if(p->info == srch)
printf("Node %d contains %d\n", p, srch);
if(p->next == NULL)
return;
p=p->next;
search(p, srch);
}
/*~~~~~~~~~DELETE ELEMENT~~~~~~~~*/
delete(NODE *top, NODE *cur)
{
if(top == cur) //delete first node
{cur->next = NULL; printf("~You now need to change top to &Node2~\n");}
else //delete intermediary or last node
while(top->next->info != cur->info)
top=top->next;
top->next = cur->next;
cur->next = NULL;
}
/*~~~~~~~~~INSERT ELEMENT~~~~~~~~*/
insert(NODE *top, NODE *postnew, int *pval)
{
printf("Input new nodes info: ");
scanf("%d", pval);
NODE new;
new.info = *pval;
new.next = postnew;
while(top->next->info != postnew->info)
top=top->next;
top->next = &new;
}