队列 栈的增删改查
双向链表的增删
在宏定义与函数之间掉进了坑里,没有区分好函数和宏定义
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
#define LL_ADD(item, list) do{ \
item->prev = NULL; \
item->next = list; \
if(list != NULL) list->prev = item; \
list = item; \
} while(0)
#define LL_REMOVE(item, list) do{ \
if(item->prev != NULL) item->prev->next = item->next; \
if(item->next != NULL) item->next->prev = item->prev; \
if(item == list) list = item->next; \
item->prev = item->next = NULL; \
} while(0)
struct list_node {
int data;
struct list_node *prev;
struct list_node *next;
};
struct head_node {
int length;
struct list_node *next;
};
// create
struct head_node* create_node() {
struct head_node *p = (struct head_node*)malloc(sizeof(struct list_node));
p->length = 0;
p->next = NULL;
return p;
}
// add
int add_node(struct head_node *p, int num) {
if (p == NULL) return -1;
struct list_node *new_node = (struct list_node*)malloc(sizeof(struct list_node));
new_node->data = num;
new_node->prev = new_node->next = NULL;
LL_ADD(new_node, p->next);
p->length++;
return 0;
}
// remove
int remove_node(struct head_node *p, int num) {
int count;
struct list_node *node = p->next;
while (node != NULL) {
if (node->data == num) break;
node = node->next;
}
if(node == NULL) return -1;
LL_REMOVE(node, p->next);
return 0;
}
void print_node(struct head_node *p) {
struct list_node *node = p->next;
while(node != NULL) {
printf("%d\n", node->data) ;
node = node->next;
}
}
int main(int argc, char* argv[]) {
struct head_node *p = create_node();
srand(time(NULL));
int count = 0;
int num;
if (argc < 2) {
printf("no argu!\n");
return -1;
}
for (count = 0; count < atoi(argv[1]); count++) {
num = (int)(rand()%10);
add_node(p, num);
}
print_node(p);
putchar(10);
remove_node(p, 5);
print_node(p);
return 0;
}