Linear Linked List
unknown
c_cpp
2 years ago
2.8 kB
13
Indexable
#include <stdio.h>
#include <stdlib.h>
struct node
{
int info;
struct node *next;
};
typedef struct node *NODEPTR;
NODEPTR list;
NODEPTR getnode (void);
void insert_list ();
int delete_list ();
void traverse ();
void insafter (int);
int delafter (int);
void freenode (NODEPTR);
int
main ()
{
int y, x;
int choice;
list = getnode ();
do
{
printf ("\n 1. Insert a node at the beginning of the linked list");
printf ("\n 2. Delete a node from the beginning of the node.");
printf ("\n 3. Show the linked list");
printf ("\n 4. Insert a node after a specified node p");
printf ("\n 5. Delete a node after a specified node p");
printf ("\n 6. Exit");
printf ("\n Enter your choice: ");
scanf ("%d", &choice);
switch (choice)
{
case 1:
insert_list ();
break;
case 2:
y = delete_list ();
printf ("\n the deleted node: %d\n", y);
break;
case 3:
traverse ();
break;
case 4:
printf ("\n Insert the value of the node that you want to specify");
fflush (stdin);
scanf ("%d", &x);
insafter (x);
break;
case 5:
printf ("\n Insert the value of the node that you want to specify");
fflush (stdin);
scanf ("%d", &x);
y = delafter (x);
printf ("\n the deleted node: %d\n", y);
break;
case 6:
printf("\nExited\n");
exit (0);
}
}
while (choice != 6);
return 0;
}
void
insert_list ()
{
NODEPTR p;
int x;
p = getnode ();
printf ("\n Enter an element: ");
scanf ("%d", &x);
p->info = x;
p->next = list->next;
list->next = p;
}
int
delete_list ()
{
NODEPTR p;
int x;
p = list->next;
if (p == NULL)
{
printf ("\n List is empty");
return -1;
}
x = p->info;
list->next = p->next;
freenode (p);
return x;
}
void
traverse ()
{
NODEPTR p;
p = list->next;
while (p != NULL)
{
printf ("%d ==>", p->info);
p = p->next;
}
}
void
insafter (int x)
{
NODEPTR p, q;
int x1;
p = list;
while (p != NULL && p->info != x)
{
p = p->next;
}
if (p == NULL)
{
printf ("\n Node with value %d not found", x);
return;
}
q = getnode ();
printf ("\n Enter an element: ");
scanf ("%d", &x1);
q->info = x1;
q->next = p->next;
p->next = q;
}
int
delafter (int x)
{
NODEPTR p, q;
int x1;
p = list;
while (p != NULL && p->info != x)
{
p = p->next;
}
if (p == NULL || p->next == NULL)
{
printf ("\n Node with value %d not found or no node after it", x);
return -1;
}
q = p->next;
x1 = q->info;
p->next = q->next;
freenode (q);
return x1;
}
NODEPTR
getnode (void)
{
NODEPTR p;
p = (NODEPTR) malloc (sizeof (struct node));
p->next = NULL;
return p;
}
void
freenode (NODEPTR p)
{
free (p);
}
Editor is loading...
Leave a Comment