abbyjones72

Doubly-Linked Lists Learning

Jul 12th, 2020
810
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.17 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. typedef struct listitem
  6. {
  7.     struct listitem *next;
  8.     struct listitem *prev;
  9.     int data;
  10. } LISTITEM;
  11.  
  12. int main()
  13. {
  14.     LISTITEM *temp, head;
  15.  
  16.     head.next = (LISTITEM*)&head;   // contains the address of head
  17.     head.prev = (LISTITEM*)&head;   // also contains the address of head
  18.     head.data = -1;
  19.  
  20.     // populate the list
  21.     for(int i = 0; i < 3; i++)
  22.     {
  23.         temp = malloc(sizeof(LISTITEM));
  24.         temp->data = i;
  25.         temp->next = head.next;
  26.         head.next = temp;
  27.         temp->prev = &head;
  28.         temp->next->prev = temp;
  29.     }
  30.  
  31.     // now lets see what we have going forward
  32.     temp = head.next;
  33.     while(temp != &head)
  34.     {
  35.         printf("forward list item: current is %p; next is %p; prev is %p; data is %d\n", temp, temp->next, temp->prev, temp->data);
  36.         temp = temp->next;
  37.     }
  38.  
  39.     // and going backwards
  40.     temp = head.prev;
  41.     while(temp != &head)
  42.     {
  43.         printf("forward list item: current is %p; next is %p; prev is %p; data is %d\n", temp, temp->next, temp->prev, temp->data);
  44.         temp = temp->prev;
  45.     }
  46.     return 0;
  47. }
Add Comment
Please, Sign In to add comment