链表的增、删、改、查(双向链表)和反转(单向链表)
#define SUCCESS 0
#define FAILED 1
typedef struct STD
{
int num;
struct STD *next, *prv;
} LIST;
int ListCreat(LIST **list)
{
LIST *head = NULL;
head = (LIST *)malloc(sizeof(LIST));
if (!head)
return FAILED;
head->next = NULL;
head->prv = NULL;
head->num = 0;
*list = head;
return SUCCESS;
}
int ListInsert(LIST *head, int cnt)
{
LIST *new = NULL;
while (cnt--) {
if (!(new = (LIST *)malloc(sizeof(LIST))))
return FAILED;
if (head->next != head->prv) {
head->next->prv = new;
new->num = head->next->num + 1;
} else {
new->num = head->num + 1;
}
new->next = head->next;
head->next = new;
new->prv = head;
}
return SUCCESS;
}
int ListSearch(LIST *head, int num)
{
LIST *node = head;
while (node && node->num != num)
node = node->next;
if (node)
printf("Found the node num: %d\n", node->num);
return SUCCESS;
}
/* Single list funtion */
LIST *ListReverse(LIST *head)
{
LIST *next = NULL, *prv = NULL, *node = head;
while (node) {
next = node->next;
node->next = prv;
prv = node;
node = next;
printf("Reserve node num: %d\n", prv->num);
}
return prv;
}
int ListDel(LIST *head)
{
LIST *node = NULL;
while (head->next != head->prv) {
node = head->next;
if (node->next)
node->next->prv = head;
head->next = node->next;
printf("delete node serial num: %d\n", node->num);
free(node);
}
return SUCCESS;
}
void main(void)
{
int ret = 0, cnt = 0;
LIST *list = NULL;
ret |= ListCreat(&list);
if (ret) goto END;
printf("Input insert node count:");
scanf("%d", &cnt);
ret |= ListInsert(list, cnt);
if (ret) goto END;
printf("Input search node num:");
scanf("%d", &cnt);
ret |= ListSearch(list, cnt);
if (ret) goto END;
list = ListReverse(list);
if (!list) goto END;
ret |= ListDel(list);
if (ret) goto END;
if (list)
free(list);
END:
return;
}