addFirst
Lesson 5 of 14 in Coddy's Doubly Linked List - Data Structures Series #6 course.
Challenge
EasyAdd a method addFirst to the DoublyLinkedList class.
It gets an integer value and inserts a new node carrying that value at the front of the list. Make sure to wire both directions of the link (prev on the old head, next on the new node), and update tail if the list was empty.
Try it yourself
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "doublylinkedlist.h"
int main() {
DoublyLinkedList ll;
DoublyLinkedList_init(&ll);
char line[256];
while (fgets(line, sizeof(line), stdin)) {
line[strcspn(line, "\r\n")] = '\0';
char* cmd = strtok(line, " \t");
if (!cmd) continue;
if (strcmp(cmd, "state") == 0) printf("%s %s %d\n", ll.head == NULL ? "true" : "false", ll.tail == NULL ? "true" : "false", ll.count);
if (strcmp(cmd, "count") == 0) printf("%d\n", ll.count);
if (strcmp(cmd, "headValue") == 0) printf("%d\n", Node_getValue(ll.head));
if (strcmp(cmd, "tailValue") == 0) printf("%d\n", Node_getValue(ll.tail));
if (strcmp(cmd, "addFirst") == 0) {
char* arg = strtok(NULL, " \t");
DoublyLinkedList_addFirst(&ll, atoi(arg));
}
}
return 0;
}