Advertisement
Shailrshah

Implementing Linked List using an Array

Aug 7th, 2013
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.07 KB | None | 0 0
  1. #include <stdio.h>
  2. #define SIZE 10
  3. struct node{
  4.     int info,next;
  5. }n[SIZE];
  6. int avail = 0;
  7. int assignNodeNext()
  8. {
  9.     int i;
  10.     for(i=0; i<(SIZE - 1); i++)
  11.         n[i].next = i+1;
  12.     n[SIZE - 1].next = -1;  
  13. }
  14. int getNode()
  15. {
  16.     int p;
  17.     if (avail == -1)
  18.     {
  19.         printf("Error: Overflow.\n");
  20.         return avail;
  21.     }
  22.     p = avail;
  23.     printf("Enter the value: ");
  24.     scanf("%d", &n[p]);
  25.     avail = n[avail].next;
  26.     return p;
  27. }
  28. int freeNode(int p)
  29. {
  30.     n[p].next = avail;
  31.     avail = p;
  32.     n[p].info = 0;
  33.     return 0;
  34. }
  35. void display()
  36. {
  37.     int i;
  38.     for(i = 0; i<SIZE; i++)
  39.         printf("| %d ",n[i]);
  40.     printf("|");
  41. }
  42. void choice()
  43. {
  44.     int choice = 0;
  45.     int p;
  46.     while (choice != -1)
  47.     {
  48.         printf("\n1. Insert. 2. Delete 3. display: ");
  49.         scanf("%d",&choice);
  50.         if (choice == 1)
  51.             getNode();
  52.         if (choice == 2)
  53.         {
  54.             printf("Delete which node?: ");
  55.             up: scanf("%d", &p);
  56.             if(p>-1 && p<SIZE)
  57.                 freeNode(p);
  58.             else
  59.             {
  60.                 printf("\nWrong input. Try again.");
  61.                 goto up;
  62.             }
  63.         }
  64.         if (choice == 3)
  65.             display();
  66.     }
  67. }
  68. int main()
  69. {
  70.     assignNodeNext();
  71.     choice();
  72.     return 0;
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement