双向循环链表的基础代码

双向循环链表:
1、设计节点
2、初始化空链表
3、新建一个节点
4、插入节点
5、删除节点
6、移动节点
7、查找节点
8、遍历链表

代码:
#include
#include
#include
#include
#include

typedef struct node
{
int data;
struct node *prev;
struct node *next;
}NODE,*PNODE;
//初始化
PNODE init_two_list(void)
{
PNODE p = (PNODE)malloc(sizeof(NODE));
p->prev = p->next = p;
return p;
}
//new节点
PNODE make_node(int data)
{
PNODE new = (PNODE)malloc(sizeof(NODE));
new->data = data;
new->prev = new->next = new;
return new;
}
//后插
void insert_node_next(PNODE p,PNODE new)
{
new->prev = p;
new->next = p->next;
p->next = new;
new->next->prev = new;
printf(“insert_node_next succes!\n”);
}
//前插
void insert_node_prev(PNODE p,PNODE new)
{
new->prev = p->prev;
new->next = p;
p->prev->next = new;
new->prev = new;
printf(“insert_node_prev succes!\n”);
}
//查找
PNODE find_node(PNODE p,int data)
{
PNODE t=p;
while(t->next != p)
{
t=t->next;
if(t->data == data)
{
printf(“find succes!\n”);
break;
}
}
return t == p?NULL:t;
}
//删除
void remove_node(PNODE delete_node)
{
delete_node->prev->next = delete_node->next;
delete_node->next->prev = delete_node->prev;
delete_node->prev = NULL;
delete_node->next = NULL;
printf(“remove secces!\n”);
}
//按传进的数据删除
//buf在主函数中定义为struct node * 型,如果要在函数中改变buf的值,就要用指针传递,所以要用struct node **
//如果只是struct node *传进函数,就只是值传递,只在函数中改变了数值。
bool delete(PNODE p,int data,PNODE *buf)
{
PNODE t=p;
while(t->next != p)
{
if(t->data == data)
{
*buf = t;
t->prev->next = t->next;
t->next->prev = t->prev;
t->prev = NULL;
t->next = NULL;
printf(“remove secces!\n”);
break;
}
if(t->next == p)
{
return false;
}
return true;
}

}
//遍历
void show_list(PNODE p)
{
PNODE t=p;
while(t->next!=p)
{
t=t->next;
printf("%d\t",t->data);
}
printf("\n");
}
//前移
void move_node_next(PNODE pos,PNODE p)
{
remove_node§;
insert_node_next(pos,p);
printf(“move_node_next secces!\n”);
}
//后移
void move_node_prev(PNODE pos,PNODE p)
{
remove_node§;
insert_node_prev(pos,p);
printf(“move_node_prev secces!\n”);
}
int main(void)
{
PNODE test,new1,new2,new3,find1,find2,find3;
test = init_two_list();

new1=make_node(1);
new2=make_node(2);
new3=make_node(3);

insert_node_next(test,new1);
insert_node_next(test,new2);
insert_node_prev(test,new3);

show_list(test);

find1=find_node(test,1);
find2=find_node(test,2);
find3=find_node(test,3);

move_node_next(find2,find1);
show_list(test);
move_node_prev(find2,find3);
show_list(test); 

//remove_node(find1);
//show_list(test);
return 0;

}

你可能感兴趣的:(双向循环链表的基础代码)