// Arup Guha
// 3/13/2024
// Solution to COP 3502H Exam 2 Question 4

#include <stdio.h>
#include <stdlib.h>

typedef struct dll {
	char name[100];
	struct dll* prev;
	struct dll* next;
} dll;

// For testing, inserts the node pointed to by node to the front of the list pointed to by front.
dll* insertfront(dll* front, dll* node) {
    if (front == NULL) return node;
	node->next = front;
	front->prev = node;
	return node;
}

// Returns a node storing myname.
dll* makenode(char* myname) {
	dll* tmp = malloc(sizeof(dll));
	strcpy(tmp->name, myname);
	tmp->next = NULL; tmp->prev = NULL;
	return tmp;
}

// Frees the memory for the list pointed to by front.
void freeList(dll* front) {
    if (front == NULL) return;
    freeList(front->next);
    free(front);
}

// Solution to Question 4
void printLoop(dll* current) {

	dll* tmp;

	// Go from current spot to right end.
	for (tmp=current; tmp->next!=NULL; tmp=tmp->next)
		printf("%s ", tmp->name);

    // Go all the way back left.
	for (;tmp->prev!= NULL; tmp=tmp->prev)
		printf("%s ", tmp->name);

    // Now back to the right stopping at our starting point.
	for (;tmp!=current; tmp=tmp->next)
		printf("%s ", tmp->name);

    // Last loop didn't print it so we do here.
	printf("%s ", tmp->name);
}

int main() {

    // Make nodes.
	dll* mine = NULL;
	dll* n1 = makenode("last");
	dll* n2 = makenode("third");
	dll* n3 = makenode("second");
	dll* n4 = makenode("first");

	// Create subway line via insertion.
	mine = insertfront(mine, n1);
	mine = insertfront(mine, n2);
	mine = insertfront(mine, n3);
	mine = insertfront(mine, n4);

	// Test from all four places!
	printLoop(n4);
	printf("\n");
	printLoop(n3);
	printf("\n");
	printLoop(n2);
	printf("\n");
	printLoop(n1);
	printf("\n");
	freeList(mine);

	return 0;
}

