Advertisement
Ikki_uni

X1

May 22nd, 2015
223
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.19 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <assert.h>
  4.  
  5. // a concrete linked list
  6. // list is a pointer to a struct - containing the head ptr
  7.  
  8. typedef struct _node *link;    // a link points ot a node
  9.  
  10. typedef struct _node {
  11.     int value;
  12.     link next;
  13. } node;
  14.  
  15. // a list is represented by a pointer to a struct which contains
  16. // a pointer to the first node of the list called the "head"
  17. typedef struct _list {
  18.     link head;
  19. } *list;
  20.  
  21. // print out a list
  22. void showList (list listToPrint) {
  23.     assert(listToPrint!=NULL);
  24.     link current = listToPrint->head;
  25.     while (current!=NULL) {
  26.         printf("[%d] -> ", current->value);
  27.         current = current->next;
  28.     }
  29.     printf("X\n");
  30. }
  31.  
  32. // inset item at the front of the list
  33. void frontInsert (list l, int item) {
  34.     // Create the node
  35.     link ptrNewNode = malloc(sizeof(node));
  36.     assert(ptrNewNode!=NULL);
  37.     ptrNewNode->value = item;
  38.    
  39.     // Add the new node
  40.     link oldHead = l->head;
  41.     l->head = ptrNewNode;
  42.     ptrNewNode->next = oldHead;
  43. }
  44.  
  45. // count the number of items in the list
  46. int numItems (list l) {
  47.     int num = 0;
  48.     link current = l->head;
  49.     while (current!=NULL) {
  50.         current = current->next;
  51.         num++;
  52.     }
  53.     return num;
  54. }
  55.  
  56. // insert at end of list
  57. void append (list l, int value) {
  58.     // Create the node
  59.     link ptrNewNode = malloc(sizeof(node));
  60.     assert(ptrNewNode!=NULL);
  61.     ptrNewNode->value = value;
  62.     ptrNewNode->next = NULL;
  63.    
  64.     // Add the node to the end of the list
  65.     link current = l->head;
  66.     if (current == NULL) {
  67.         current = ptrNewNode;
  68.     } else {
  69.         while (current->next!=NULL) {
  70.             current = current->next;
  71.         }
  72.         // Now current points to the last node, just add it
  73.         current->next = ptrNewNode;
  74.     }
  75. }
  76.  
  77. // find the value stored at position i
  78. // i MUST be a valid position in the list
  79. // dont call this on positions outside the list
  80. int lookup (list l, int position) {
  81.     assert(position>=0);
  82.     link current = l->head;
  83.     int currentPos = 0;
  84.     while (currentPos < position) {
  85.         current = current->next;
  86.         currentPos++;
  87.     }
  88.     return (current->value);
  89. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement