peppermints
Member
I'm having some trouble wrapping my head around linked lists in C... I have a basic program made that creates a linked list, allows you to add nodes, delete nodes, etc:
I'm also trying to get it to add a node after specific number, meaning that the program will search for that number then insert a node after it. This is what I'm trying to accomplish in my addAfter function. However, I keep getting segmentation faults in addition to nothing happening when I call that function.
Any ideas?
Code:
struct link
{
int item;
struct link *next;
};
typedef struct link node;
node *head=NULL;
void addfirst()
{
node *temp;
temp=(node *)malloc(sizeof(node));
printf("Enter the data....\t");
scanf("%d",&temp->item);
temp->next=head;
head=temp;
}
void addend()
{
node *temp,*cur=head;
temp=(node *)malloc(sizeof(node));
printf("\nEnter the data....");
scanf("%d",&temp->item);
while(cur->next!=NULL)
{
cur=cur->next;
}
temp->next=cur->next;
cur->next=temp;
}
void delBeg()
{
node *temp=head;
head=head->next;
free(temp);
}
void delLast()
{
node *temp,*cur=head;
while(cur->next->next!=NULL)
{
cur=cur->next;
}
temp=cur->next;
cur->next=NULL;
free(temp);
}
int addAfter(int num)
{
node *temp;
temp = head;
while(temp !=NULL)
{
if (temp->item==num)
{
node *p;
p=(struct node*)malloc(sizeof(node));
printf("enter data");
scanf("%d", &(p->item));
p->next=NULL;
p->next=temp->next;
temp->next=p;
}
else
temp=temp->next;
}
}
void display()
{
node *cur=head;
printf("\nHead->");
while(cur!=NULL)
{
printf("\t%d",cur->item);
cur=cur->next;
}
printf("<-NULL\n");
}
void prompt() {
printf("\n1 INSERT a node at the END of linklist\n");
printf("2 INSERT a node at the BEGINNING of linklist\n");
printf("3 DELETE a node at the END of linklist\n");
printf("4 DELETE a node from the BEGINNING of linklist\n");
printf("5 INSERT a node in the MIDDLE of linklist\n");
printf("6 DELET a node from the MIDDLE of linklist\n");
printf("7 MODIFY any node in linklist\n");
printf("8 EXIT\n");
}
int ask_num(){
struct link *node;
int num;
printf("Enter a positive integer: ");
scanf("%d", &num);
return num;
}
int linkedLists(){
struct link *node;
int choice;
int num;
do {
prompt();
scanf("%d", &choice);
switch (choice) {
case 1:
addend();
display();
break;
case 2:
addfirst();
display();
break;
case 3:
delLast();
display();
break;
case 4:
delBeg();
display();
case 5:
addAfter(num);
display();
case 8:
break;
}
}
while (choice != 8);
return 0;
}
I'm also trying to get it to add a node after specific number, meaning that the program will search for that number then insert a node after it. This is what I'm trying to accomplish in my addAfter function. However, I keep getting segmentation faults in addition to nothing happening when I call that function.
Any ideas?