Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h> // for malloc(), free()
- typedef struct Node {
- int data;
- struct Node *next;
- } Node_t;
- typedef int bool_t;
- // TODO:
- /// Handle case exceptions when HEAD is empty in pop(), push()
- // Add boolean isEmpty()
- // Add function: clear() which clears the linked list (leaves nothing, and cleans up memory)
- // Add function: length() which returns how many element does the list possess
- // Add function: addMany(@param array) which adds elements of the array (or another linked list)
- // ...
- bool_t isEmpty(Node_t *node) {
- return node == NULL;
- }
- Node_t *createNode(int data, Node_t *next_node) {
- Node_t *node = (Node_t *)malloc(sizeof(Node_t));;
- node->data = data;
- node->next = next_node;
- }
- void push(Node_t *head, int data) {
- Node_t *new_node = createNode(data, NULL);
- Node_t *it = head;
- while (it->next != NULL) {
- it = it->next;
- }
- it->next = new_node;
- }
- void printList(Node_t *head) {
- Node_t *it = head;
- while (!isEmpty(it)) {
- printf("%d->", it->data);
- it = it->next;
- }
- printf("\n");
- }
- int pop(Node_t *head) {
- int ret;
- // Handle case if HEAD has only 1 element
- if (head->next == NULL) {
- ret = head->data;
- free(head);
- return ret;
- }
- Node_t *it = head;
- while (it->next->next != NULL) {
- it = it->next;
- }
- ret = it->next->data;
- free(it->next);
- it->next = NULL;
- return ret;
- }
- int main(void) {
- Node_t *HEAD = createNode(10, NULL);
- push(HEAD, 20);
- push(HEAD, 3);
- printList(HEAD);
- // prints: 10->20->3
- pop(HEAD); // pops 3
- printList(HEAD); // prints: 10->20
- return 0;
- }
Add Comment
Please, Sign In to add comment