hozer

DDS - GetById (1-way linked list)

Apr 15th, 2014
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.66 KB | None | 0 0
  1. #define _CRT_SECURE_NO_WARNINGS
  2. #include <stdio.h>
  3. #include <string.h>
  4. #include <stdlib.h>
  5.  
  6. typedef struct _node {
  7.     char data[64];
  8.     struct _node *next;
  9. } node;
  10.  
  11. node *addNode(node *head)
  12. {
  13.     node * el = head;
  14.     node * n = (node*) malloc(sizeof(node));
  15.     n->next = NULL;
  16.     printf("input data: "); scanf("%s", n->data);
  17.     if (head)
  18.     {
  19.         while (el->next)
  20.             el = el->next;
  21.         el->next = n;
  22.         return head;
  23.     }
  24.     else
  25.     {
  26.         return n;
  27.     }
  28. }
  29.  
  30. void removeNode(node **head, node *del)
  31. {
  32.     node *el = *head;
  33.  
  34.     if (*head == del)
  35.     {
  36.         *head = del->next;
  37.     }
  38.     else
  39.     {
  40.         while (el->next && el->next != del)
  41.             el = el->next;
  42.  
  43.         if (!el->next) return;
  44.         el->next = del->next;
  45.     }
  46.     free(del);
  47. }
  48.  
  49.  
  50. node *getNodeById(node *head, int pos)
  51. {
  52.     int i;
  53.     char flag;
  54.     node *lim = head, *found = head;
  55.  
  56.     flag = pos >= 0 ? 1 : -1;
  57.     pos *= flag;
  58.  
  59.     for (i = 0; lim; i++, lim = lim->next)
  60.     {
  61.         if (flag == 1 && i >= pos)
  62.         {
  63.             found = lim;
  64.             break;
  65.         }
  66.         else if (flag == -1 && i >= pos)
  67.             found = found->next;
  68.     }
  69.  
  70.     if (i < pos) return NULL;
  71.     else return found;
  72. }
  73.  
  74.  
  75. void printList(node *head)
  76. {
  77.     node *el = head;
  78.     while (el)
  79.     {
  80.         printf("%s\n", el->data);
  81.         el = el->next;
  82.     }
  83. }
  84.  
  85.  
  86. int main()
  87. {
  88.     int n, i, fi;
  89.     node *head = NULL, *f = NULL;
  90.    
  91.     printf("input n: "); scanf("%d", &n);
  92.     for (i = 0; i < n; i++)
  93.     {
  94.         head = addNode(head);
  95.     }
  96.  
  97.     printf("Input position: "); scanf("%d", &fi);
  98.     f = getNodeById(head, fi);
  99.     if (f)
  100.         printf("Founded = %s\n", f->data);
  101.     else
  102.         printf("Error: list index out of range.\n");
  103.     printList(head);
  104.  
  105.     printf("\n---REMOVE---\n");
  106.     removeNode(&head, head);
  107.     printList(head);
  108.  
  109.     _getch();
  110.     return 0;
  111. }
Advertisement
Add Comment
Please, Sign In to add comment