实验楼楼赛 第14期-双向链表

题目链接双向链表
这道题一开始没有灵感,于是网上搜了下答案.没搜到.于是只好自己乖乖的慢慢改bug.发现List表的head表头和tail表尾是都不为空的,都是指向了具体的节点的,而且这是一个双向循环链表,结尾的遍历和释放都明显错了.代码贴在下面啦:

list.c

#include "list.h"

struct List*
init_list () {
    struct List* list = (struct List *) malloc (sizeof (struct List));
	
	list->head = list->tail = NULL;
    return list;
}

void
free_list (struct List* list) {
    struct Node* current = list->head;
    struct Node* pcurrent = current;
	
	current = current->next;
	free(pcurrent);
	

    while (current != list->head) {
		pcurrent = current;
		current = current->next;
        free (pcurrent);
    }
    free (list);
}

void
traverse_list (struct List* list, void (*callback)(void* data)) {
    struct Node* current = list->head;
    while (current) {
        (*callback)(current->data);
        current = current->next;
		if(current == list->head)
			break;
    }
}

void
insert_after (struct List* list, struct Node* prev, void* data) {
	struct Node* next = prev ? prev->next : list->head;

    struct Node* newnode = (struct Node *) malloc (sizeof (struct Node));
    newnode->data = data;

	newnode->prev = prev ? prev : list->tail;
    newnode->next = next;

    prev ? prev->next = newnode : list->tail ? list->tail->next = newnode : NULL;
    next ? next->prev = newnode : 0 ;

    list->head == NULL ? list->head = list->tail = newnode :
        prev == NULL ? list->tail = newnode : 0 ;
}

void
insert_before (struct List* list, struct Node* next, void* data) {
    struct Node* prev = next ? next->prev : list->tail;

    struct Node* newnode = (struct Node *) malloc (sizeof (struct Node));
    newnode->data = data;

	newnode->prev = prev;
	newnode->next = next ? next : list->head;
	
	next ? next->prev = newnode : list->head ?  list->head->prev = newnode : NULL;
    prev ? prev->next = newnode : 0 ;

    list->tail == NULL ? list->head = list->tail = newnode :
        next == NULL ? list->head = newnode : 0 ;
}

void
insert_front (struct List* list, void* data) {
    insert_before (list, NULL, data);
}

void
insert_back (struct List* list, void* data) {
    insert_after (list, NULL, data);
}

void
delete_from (struct List* list, struct Node* node) {
    struct Node* prev = node->prev;
    struct Node* next = node->next;

    prev ? prev->next = next : 0 ;
    next ? next->prev = prev : 0 ;

    node == list->head ? list->head = next : 0;
    node == list->tail ? list->tail = prev : 0;

    free (node);
}

其余两个文件不用改动
实现效果:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值