]> 4ch.mooo.com Git - 16.git/blob - src/lib/ll.c
working on palllist.c
[16.git] / src / lib / ll.c
1 #include "src/lib/ll.h"\r
2 \r
3 void print_list(node_t * head)\r
4 {\r
5         node_t * current = head;\r
6 \r
7         while (current != NULL)\r
8         {\r
9                 printf("%d\n", current->val);\r
10                 current = current->next;\r
11         }\r
12 }\r
13 \r
14 void pushe(node_t * head, int val)\r
15 {\r
16         node_t * current = head;\r
17         while (current->next != NULL)\r
18         {\r
19                 current = current->next;\r
20         }\r
21 \r
22         // now we can add a new variable\r
23         current->next = malloc(sizeof(node_t));\r
24         current->next->val = val;\r
25         current->next->next = NULL;\r
26 }\r
27 \r
28 void pushs(node_t ** head, int val)\r
29 {\r
30         node_t * new_node;\r
31         new_node = malloc(sizeof(node_t));\r
32 \r
33         new_node->val = val;\r
34         new_node->next = *head;\r
35         *head = new_node;\r
36 }\r
37 \r
38 int pop(node_t ** head)\r
39 {\r
40         int retval = -1;\r
41         node_t * next_node = NULL;\r
42 \r
43         if (*head == NULL) {\r
44                 return -1;\r
45         }\r
46 \r
47         next_node = (*head)->next;\r
48         retval = (*head)->val;\r
49         free(*head);\r
50         *head = next_node;\r
51 \r
52         return retval;\r
53 }\r
54 \r
55 int remove_last(node_t * head)\r
56 {\r
57         int retval = 0;\r
58         node_t * current;\r
59 \r
60         /* if there is only one item in the list, remove it */\r
61         if (head->next == NULL) {\r
62                 retval = head->val;\r
63                 free(head);\r
64                 return retval;\r
65         }\r
66 \r
67         /* get to the last node in the list */\r
68         current = head;\r
69         while (current->next->next != NULL) {\r
70                 current = current->next;\r
71         }\r
72 \r
73         /* now current points to the last item of the list, so let's remove current->next */\r
74         retval = current->next->val;\r
75         free(current->next);\r
76         current->next = NULL;\r
77         return retval;\r
78 \r
79 }\r
80 \r
81 int remove_by_index(node_t ** head, int n)\r
82 {\r
83         int i = 0;\r
84         int retval = -1;\r
85         node_t * current = *head;\r
86         node_t * temp_node = NULL;\r
87 \r
88         if (n == 0) {\r
89                 return pop(head);\r
90         }\r
91 \r
92         for (i = 0; i < n-1; i++) {\r
93                 if (current->next == NULL) {\r
94                         return -1;\r
95                 }\r
96                 current = current->next;\r
97         }\r
98 \r
99         temp_node = current->next;\r
100         retval = temp_node->val;\r
101         current->next = temp_node->next;\r
102         free(temp_node);\r
103 \r
104         return retval;\r
105 }\r