#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define COLOR(a,b) "\033[" #b "m" a "\033[0m"
#define GREEN(a) COLOR(a,32)
typedef struct Node {
int data;
struct Node* next;
} Node;

typedef struct List {
Node head;//定义虚拟头节点
int length;
}List;

Node* getNewNode(int);
List* init_list();
int insert(List*, int, int);
int erase(List*, int);
void clear_node(Node*);
void clear_List(List*);
void output(List*);

Node* getNewNode(int val) {
Node* node = (Node*)malloc(sizeof(Node));
node->data = val;
node->next = NULL;
return node;
}

List* init_list() {
List* list = (List*)malloc(sizeof(List));
list->head.next = NULL;
list->length = 0;
return list;
}

int insert(List* l, int ind, int val) {
if (l == NULL) return 0;
if(ind < 0 || ind > l->length) return 0;
Node* p = &(l->head), * node = getNewNode(val);
while (ind--) p = p->next;
node->next = p->next;
p->next = node;
l->length += 1;
return 1;
}

int erase(List* l, int ind) {
if (l == NULL) return 0;
if (ind < 0 || ind >= l->length) return 0;
Node* p = &(l->head), * q;
while (ind--) p = p->next;
q = p->next;
p->next = q->next;
clear_node(q);
l->length -= 1;
return 1;
}


void clear_node(Node* node) {
if (node == NULL) return;
free(node);
return;
}

void clear_list(List* list) {
if (list == NULL) return;
Node* p = list->head.next, * q;
while (p) {
q = p->next;
free(p);
p = q;
}
free(list);
return;
}

void output(List* l) {
if (l == NULL) return;
printf("list(%d):", l->length);
for (Node* p = l->head.next; p; p = p->next) {
printf("%d->", p->data);
}
printf("NULL\n");
return;
}

void reverse(List* l) {
if (l == NULL) return;
Node* p = l->head.next, * q;
l->head.next = NULL;
while (p) {
q = p->next;
p->next = l->head.next;
l->head.next = p;
p = q;
}
return ;
}
int main() {
srand(time(0));
#define MAX_OP 20
List* l = init_list();
for (int i = 0; i < MAX_OP; i++) {
int val = rand() % 100;
int ind = rand() % (l->length + 3) - 1;
int op = rand() % 4;
switch (op) {
case 0:
case 1: {
printf(GREEN("reverse the list!\n"));
reverse(l);
}break;
case 2: {
printf("insert %d at %d to List = %d\n", val, ind, insert(l, ind, val));
}break;
case 3: {
printf("erase a item at %d from List = %d\n", ind, erase(l, ind));
}break;
}
output(l);
printf("\n");
}
return 0;
}