天天看点

双端队列(dequeue)链表实现

#include<iostream>
#define NULLDATA -1

using namespace std;
typedef int ElemType;
typedef struct node *link;
typedef struct Dqueue DoubleList;

typedef struct node
{
 ElemType data;
 link next;

}node;

typedef struct Dqueue
{
 link dq;        //dq为辅助指针,1、开始时进行初始化2、删除时也用到了
 link head,end;
 
}Dqueue;

DoubleList *ob = (DoubleList *)malloc(sizeof(DoubleList));

link newnode(ElemType v)  //构造link型结点 注意而不是DoubleList型。
{
  link c = (link)malloc(sizeof(node));
  c->data = v;
  c->next = NULL;
  return c;
}

void Init(DoubleList *ob)
{
  
  ob->dq = (link)malloc(sizeof(node));
  ob->dq->data = NULLDATA;
  ob->dq->next = NULL;
  ob->head = ob->end = ob->dq;

}

void Head_In( ElemType v)
{
  
  if(ob->head->data == NULLDATA  )
	 {
	  ob->head->data = v;
	  
	  return ;
  }
  else
  {
    link c = newnode(v);
	c->next = ob->head;
    ob->head = c;
	return ;
  }
 
}

ElemType Head_Out( )
{ 
  ElemType c = ob->head->data;
  ob->head = ob->head->next;
  return c;

}

void End_In( ElemType v)
{ 
  
  if(ob->end->data == NULLDATA)
      ob->end->data = v;
  else
  {  link c = newnode(v); 
      ob->end->next = c;
      ob->dq = ob->end;
	  ob->end = ob->end->next; 
  }
 
}

ElemType End_Out( )
{ ElemType c = ob->dq->data;
  ob->dq->next = NULL;
  ob->end = ob->dq;
  return c;
}

void Show(DoubleList *h)
{
  DoubleList *ptr = h;
  for(;ptr->head != NULL; ptr->head = ptr->head->next)
  {
	  cout<<ptr->head->data<<endl;
	  
  }

}

int main()
{ 
   
   Init(ob);
   for(int j = 0; j < 10 ;j++)
   End_In(10 - j);
   for(int i = 0; i < 10 ; i++)
	   Head_In(i);
   End_Out();
   End_Out();
   End_Out();
   End_In(132);
   End_In(333);
   Head_In(99);
   Head_In(102);
   Head_In(88);
   Head_Out();
   Show(ob); 
   
   return 0;
}
           

总结:

无它,但手熟而。

继续阅读