sahajjain01

14.Implement Linear Linked List.

Aug 15th, 2016
41
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.70 KB | None | 0 0
  1. //Program to implement Linear Linked List.
  2. #include <stdio.h>
  3. #include <malloc.h>
  4. #include <conio.h>
  5.  
  6. struct student {
  7.     char name[20];
  8.     struct student *next;
  9. } *first = NULL, *last, *temp;
  10.  
  11. void insert() {
  12.     temp = (struct student *) malloc(sizeof(struct student));
  13.  
  14.     printf("Enter name: ");
  15.     scanf("%s", temp->name);
  16.  
  17.     temp->next = NULL;
  18.  
  19.     if (first == NULL) {
  20.         first = temp;
  21.         last = temp;
  22.         printf("Created first node.");
  23.         getch();
  24.     } else {
  25.         last->next = temp;
  26.         last = temp;
  27.         printf("Inserted new node.");
  28.         getch();
  29.     }
  30. }
  31.  
  32. void display() {
  33.     temp = first;
  34.  
  35.     while (temp != NULL) {
  36.         printf("%s\n", temp->name);
  37.         temp = temp->next;
  38.     }
  39.     getch();
  40. }
  41.  
  42. void search() {
  43.     char name[20];
  44.     int count = 1;
  45.  
  46.     printf("Enter name to search: ");
  47.     scanf("%s", name);
  48.  
  49.     temp = first;
  50.  
  51.     while (temp != NULL) {
  52.         if (!strcmp(name, temp->name)) {
  53.             printf ("Match found at node %d.", count);
  54.             getch();
  55.             break;
  56.         }
  57.         count++;
  58.         temp = temp->next;
  59.     }
  60.  
  61.     if (temp == NULL) {
  62.         printf("Match not found.");
  63.         getch();
  64.     }
  65. }
  66.  
  67. void erase() {
  68.     if (first->next == NULL) {
  69.         printf("The list cannot be empty.");
  70.         getch();
  71.         return;
  72.     }
  73.     temp = first;
  74.     first = first->next;
  75.     free(temp);
  76.  
  77.     printf("Deleted first node.");
  78.     getch();
  79. }
  80.  
  81. void main()
  82. {
  83.     char choice;
  84.  
  85.     while (1) {
  86.         clrscr();
  87.  
  88.         printf("1.Insert node\n2.Display list\n3.Search node\n4.Delete node\n5.Exit\n\n");
  89.         choice = getch();
  90.  
  91.         switch (choice) {
  92.             case '1':
  93.             insert();
  94.             break;
  95.  
  96.             case '2':
  97.             display();
  98.             break;
  99.  
  100.             case '3':
  101.             search();
  102.             break;
  103.  
  104.             case '4':
  105.             erase();
  106.             break;
  107.  
  108.             case '5':
  109.             return;
  110.  
  111.             default:
  112.             printf("Invalid input.");
  113.             getch();
  114.         }
  115.     }
  116. }
Add Comment
Please, Sign In to add comment