Skip to content

Instantly share code, notes, and snippets.

@kdelwat
Created October 10, 2017 21:09
Show Gist options
  • Save kdelwat/4564d53606d71640c2814e5eb1a0c2b0 to your computer and use it in GitHub Desktop.
Save kdelwat/4564d53606d71640c2814e5eb1a0c2b0 to your computer and use it in GitHub Desktop.
COMP1511 list example
#include <stdio.h>
#include <stdlib.h>
#include "List.h"
List makeList(void) {
List l = calloc(1, sizeof(list));
return l;
}
List addAtHead(List l, int value) {
Node newNode = calloc(1, sizeof(node));
newNode->value = value;
newNode->next = l->head;
l->head = newNode;
return l;
}
List deleteFromTail(List l) {
Node currentNode = l->head;
if (l->head->next == NULL) {
free(l->head);
l->head = NULL;
} else {
while (currentNode->next->next != NULL) {
currentNode = currentNode->next;
}
free(currentNode->next);
currentNode->next = NULL;
}
return l;
}
void printList(List l) {
printf("List: ");
Node currentNode = l->head;
while (currentNode != NULL) {
printf("%d ", currentNode->value);
currentNode = currentNode->next;
}
printf("\n");
}
typedef struct _node *Node;
typedef struct _list *List;
typedef struct _list {
Node head;
} list;
typedef struct _node {
int value;
Node next;
} node;
List makeList(void);
List addAtHead(List l, int value);
List deleteFromTail(List l);
void printList(List l);
#include "List.h"
int main(int argc, char** argv) {
List l = makeList();
l = addAtHead(l, 1);
printList(l);
l = addAtHead(l, 2);
printList(l);
l = addAtHead(l, 3);
printList(l);
l = deleteFromTail(l);
printList(l);
l = deleteFromTail(l);
printList(l);
l = deleteFromTail(l);
printList(l);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment