挑战高手——用c实现一个双向链表
发现用c实现一个双向链表原来蛮复杂的,支持任意位置的删除,通过指针删除其所在位置的元素,头指针还需要初始化,如果需要这个双向链表适应任意情况,将更复杂。
随时可能内存泄漏,靠。
谁有源码啊,学习一下先。
其实我也写了一个,支持尾部插入节点,任意位置删除节点,觉得还是不好。大家随便看看啦,我感觉好像随时会出现内存泄漏什么的。
-------------------------------------------
/* list.h
** Copyright 2004 Coon Xu.
** Author: Coon Xu
** Date: 06 Sep 2004
*/
typedef struct listnode {
struct listnode *next;
struct listnode *prior;
//int jobnum;
} listnode;
typedef struct list {
listnode *head;
int empty; //1 --empty, 0--not empty
} list;
void list_init(list *myroot);
void list_put(list *myroot, listnode *mynode);
int list_remove(list *myroot,listnode *mynode);
-----------------------------------------
/* list.c
** Copyright 2004 Coon Xu.
** Author: Coon Xu
** Date: 06 Sep 2004
**
*/
#include <stdio.h>
#include "list.h"
void list_init(list *myroot) {
myroot->head = malloc(sizeof(listnode));
myroot->head->prior = NULL;
myroot->head->next = NULL;
myroot->empty = 1;
}
//insert node at the tail
void list_put(list *myroot,listnode *mynode) {
mynode->next = NULL;
mynode->prior = NULL;
myroot->empty = 0;
listnode* p_node = myroot->head->next;
if(p_node == NULL)
{
myroot->head->next = mynode;
}
else
{
while(p_node->next != NULL)
{
p_node = p_node->next;
}
p_node->next = mynode;
mynode->prior = p_node;
}
}
int list_remove(list *myroot,listnode *mynode) {
/* remove from root */
listnode *p_node = mynode;
if(myroot->head->next == NULL || p_node == NULL)
{
return 0;
}
//remove the first node, obtain the list has only one node
if(p_node->prior == NULL)
{
//the list has only one
if(p_node->next == NULL)
{
myroot->head->next = NULL;
myroot->empty = 1;
}
else
{
p_node->next->prior = NULL;
myroot->head->next = p_node->next;
}
}
//remove the last node
else if(p_node->next == NULL)
{
p_node->prior->next = NULL;
}
else
{
p_node->prior->next = p_node->next;
p_node->next->prior = p_node->prior;
}
free(p_node);
return 1;
}