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

双向链表,在结构体中定义两个指针,一个指针指向前一个节点,另一个指向后一个节点。 然后动态的开辟空间来存储插入的数据。

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();
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值