list.c 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. #include <types.h>
  2. #include <kern/errno.h>
  3. #include <lib.h>
  4. #include <list.h>
  5. typedef struct list list;
  6. typedef struct node node;
  7. list * newlist(void)
  8. {
  9. list * ret = kmalloc(sizeof(list));
  10. if (!(ret)) return NULL;
  11. ret->front = NULL;
  12. ret->len = 0;
  13. return ret;
  14. }
  15. int listsert(list * l, int x)
  16. {
  17. node * temp = l->front;
  18. node * newnode = kmalloc(sizeof(node));
  19. if (!(newnode)) return ENOMEM;
  20. newnode->val = x;
  21. newnode->next = temp;
  22. l->front = newnode;
  23. ++l->len;
  24. return 0;
  25. }
  26. void listemove(list * l, int x)
  27. {
  28. node * temp = l->front;
  29. node * temp2 = NULL;
  30. while (temp)
  31. {
  32. if (temp->val == x)
  33. {
  34. if (!(temp2))
  35. {
  36. l->front = temp->next;
  37. }
  38. else
  39. {
  40. temp2->next = temp->next;
  41. }
  42. --l->len;
  43. break;
  44. }
  45. else
  46. {
  47. temp2 = temp;
  48. temp = temp->next;
  49. }
  50. }
  51. }
  52. void listelete(list * l)
  53. {
  54. node * temp = l->front;
  55. node * temp2 = NULL;
  56. while (temp)
  57. {
  58. temp2 = temp->next;
  59. kfree(temp);
  60. temp = temp2;
  61. }
  62. kfree(l);
  63. }
  64. int listearch(list * l, int x)
  65. {
  66. node * temp = l->front;
  67. while (temp)
  68. {
  69. if (temp->val == x) return 1;
  70. temp = temp->next;
  71. }
  72. return 0;
  73. }
  74. int listpop(list * l)
  75. {
  76. node * temp = l->front;
  77. if (temp)
  78. {
  79. int x = temp->val;
  80. l->front = temp->next;
  81. --l->len;
  82. kfree(temp);
  83. return x;
  84. }
  85. return 0;
  86. }