// one of the basic bits of a linked list is the node
#include <stdlib.h>
#include <assert.h>
#include <stdio.h>
struct linkedList {
// this pointer aims at the first element of the list
struct node *head;
};
struct node {
// this pointer links the chain of nodes together
struct node *next;
// the data is the information that we're storing
int data;
};
// These functions could be declared in a header file, I'm just working
// in one file for now
void addElementAtEnd(struct linkedList *list, int item);
void printList(struct linkedList *list);
int main() {
// myList is a pointer aiming at a linkedList struct in memory
struct linkedList *myList = malloc(sizeof (struct linkedList));
// setting this to NULL makes 100% sure this looks empty at the beginning
myList->head = NULL;
// Now that we have an empty list, we want to add some elements
// We're going to add elements to the tail end of the list
addElementAtEnd(myList, 1);
addElementAtEnd(myList, 2);
addElementAtEnd(myList, 3);
printList(myList);
}
// Find the last element of the list, add a new node after it
void addElementAtEnd(struct linkedList *list, int item) {
// loop until the end of the list to find where to add the node
struct node *loopingNode = list->head;
struct node *previousNode = NULL;
// stopping case: we stop looping when the node we're looking at is NULL
while (loopingNode != NULL) {
// Keep track of the node before the current one
previousNode = loopingNode;
// increment . . . move from one node to the next
loopingNode = loopingNode->next;
}
// when this loop finishes,
// loopingNode will be NULL
// previousNode will be the last node
// We've been asked to add to the end of the list, and now
// we know exactly where that is
// Now we add a node after the "previousNode" called "newNode"
struct node *newNode = malloc(sizeof (struct node));
// assert will be ignored if it's true
// if what's in the brackets is false, the program will stop here
// and report back where the failure was
// This assert is checking whether the malloc above succeeded
assert(newNode != NULL);
// now populate the node. It's next is NULL because it's at the end
// of the list
newNode->next = NULL;
newNode->data = item;
// If the list was empty before we added this node
// This node becomes the first node in the list, so it should be
// the new head
if(list->head == NULL) {
list->head = newNode;
} else {
// The list already had at least one element
// connect this node to the rest of the list
// this is done by connecting previousNode's next to this newNode
previousNode->next = newNode;
}
}
// Print out all the elements of the list
void printList(struct linkedList *list) {
// This is a very standard while loop for looping through all the elements
// We're going to use this to print out each element
struct node *loopNode = list->head;
while(loopNode != NULL) {
printf("%d\n", loopNode->data);
loopNode = loopNode->next;
}
}
Resource created Wednesday 24 April 2019, 11:10:20 PM.
file: linkedlistDemo.c