系列文章记录重回开发之路----2. 队列,栈

本文探讨了如何在宏定义与函数中正确使用LL_ADD和LL_REMOVE,以及如何在`create_node`、`add_node`和`remove_node`中实现队列栈和双向链表的基本操作,包括创建、增删节点和打印。通过实例展示了在处理数据结构时遇到的陷阱及其解决方案。
摘要由CSDN通过智能技术生成

队列 栈的增删改查

双向链表的增删

在宏定义与函数之间掉进了坑里,没有区分好函数和宏定义

#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;

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值