#include<stdio.h>
#include<time.h>
#include<stdlib.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* get_newNode(int);
List* init_list();
void clear_node(Node*);
void claer(List*);
int insert(List*, int, int);
int erase(List*, int);
void reverse(List* l);
void output(List*);
//初始化节点
Node* get_newNode(int val) {
Node* node = (Node*)malloc(sizeof(Node));
node->data = val;
node->next = NULL;
return node;
}
//初始化链表
List* init_list() {
List* l = (List*)malloc(sizeof(List));
l->head.next = NULL;
l->length = 0;
return l;
}
//项链表当中插入值
int insert(List* l, int ind, int val) {
if (l == NULL)return 0;
if (ind<0 || ind>l->length)return 0;
//特判
/*if (ind == 0) {
node->next = l->head;
l->head = node;
}*/
Node* p = &(l->head), * node = get_newNode(val);
while (ind--) {
p = p->next; //让p走到待插入位置的前一项
}
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* l) {
if (l == NULL)return;
Node* p = l->head.next, * q;
while (p != NULL) {
q = p->next;
clear_node(p);
p = q;
}
free(l);
return;
}
//调转链表中的元素
void reverse(List* l) {
if (l == NULL)return;
Node* p = l->head.next, * q;
l->head.next = NULL;
while (p != NULL) {
q = p->next;
p->next = l->head.next;
l->head.next = p;
p = q;
}
return;
}
void output(List* l) {
if (l == NULL)return;
printf("List(%d) : ", l->length);
for (Node* p = l->head.next; p != NULL; p = p->next) {
printf("%d->", p->data);
}
printf("NULL\n");
}
int main() {
srand(time(0));
#define MAX 50
List* l = init_list();
for (int i = 0; i < MAX; i++) {
int val = rand() % 100;
int ind = rand() % (l->length + 3) - 1;
int op = rand() % 4;
switch (op) {
case 1:
case 2: {
printf("insert %d at %d to the List = %d\n", val, ind, insert(l, ind, val));
output(l);
}break;
case 0: {
reverse(l);
printf(GREEN("reverse the List!\n"));
output(l);
}break;
case 3: {
printf("erase an item at %d from List = %d\n", ind, erase(l, ind));
output(l);
}break;
}
printf("\n");
}
#undef MAX
return 0;
}
链表代码演示
最新推荐文章于 2024-12-25 15:30:53 发布