C实现链表

链表的增、删、改、查(双向链表)和反转(单向链表)

#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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值