您的位置:首页 > 编程语言 > C语言/C++

多文件编程动态开辟空间实现双向链表的应用 c++版

2014-03-25 23:49 549 查看
双向链表,在结构体中定义两个指针,一个指针指向前一个节点,另一个指向后一个节点。 然后动态的开辟空间来存储插入的数据。

dqueue.h

#ifndef __DQUEUE_H__
#define __DQUEUE_H__
void init();
void deinit();
int first();
int last();
void add_head(int num);
void append(int num);
void begin_remove();
void end_remove();
#endif
dqueue.c

#include <stdio.h>
#include "dqueue.h"
#include <stdlib.h>
typedef struct node{
int num;
struct node *p_next;
struct node *p_pre;
}node;
node head,tail;
void init(){ //双向链表的初始化
head.p_next = &tail;
head.p_pre = NULL;
tail.p_next = NULL;
tail.p_pre = &tail;
}
void deinit() { // 双向链表的销毁
node *p_tmp;
while(head.p_next != &tail){
p_tmp = head.p_next;
head.p_next = p_tmp->p_next;
free(p_tmp);
p_tmp = NULL;
}
}
int first(){
if(head.p_next != &tail){
return head.p_next->num; //返回head所指下一个有效数据的值
}else{
return 0;
}
}
int last(){
if(tail.p_pre != &head){
return tail.p_pre->num; //返回tail所指上一个有效数据的值
}else{
return 0;
}
}
void add_head(int num){
node *p_tmp = (node *)malloc(sizeof(node));
p_tmp->num = num;
node *p_node = head.p_next;
head.p_next = p_tmp;
p_tmp->p_pre = &head;
p_tmp->p_next = p_node;
p_node->p_pre = p_tmp;
}
void append(int num){
node *p_tmp = (node *)malloc(sizeof(node));
p_tmp->num = num;
node *p_node = tail.p_pre;
p_node->p_next = p_tmp;
p_tmp->p_pre = p_node;
p_tmp->p_next = &tail;
tail.p_pre = p_tmp;
}
void begin_remove(){
if (head.p_next != &tail){
node *p_tmp = head.p_next;
node *p_node = p_tmp->p_next;
head.p_next = p_node;
p_node->p_pre = &head;
free(p_tmp);
p_tmp = NULL;
}
}
void end_remove(){
if (tail.p_pre != &head){
node *p_tmp = tail.p_pre;
node *p_node = p_tmp->p_pre;
p_node->p_next = &tail;
tail.p_pre = p_node;
free(p_tmp);
p_tmp = NULL;

}
}
main.c

#include <stdio.h>
#include "dqueue.h"
int main(){
init();
add_head(10);
append(33);
add_head(100);
printf("%d\n",first());
printf("%d\n",last());
end_remove();
printf("%d\n",last());
begin_remove();
printf("%d\n",first());
deinit();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息