編程之美—隊列中取最大值操作問題

思想就是入隊操作時,對最大值進行記錄。一種方法直接創建隊列,二種方法是利用2個棧實現隊列功能(詳見前面的文章)。此處給出第一種方法代碼:

// MaxQueue.cpp : 定義控制檯應用程序的入口點。
//

#include "stdafx.h"
#include<iostream>

typedef int type;
using namespace std;

//鏈棧結點
typedef struct stack
{
   type data;
   struct stack *next;
}stack,*pStack;


 
//鏈隊隊列結點
typedef struct queue
{
	type data;
	struct queue *next;
}queue,*pQueue;

//隊
typedef struct lqueue
{
	pQueue front;//隊首指針
	pQueue rear; //隊尾指針
	type Max;//最大值變量
}lqueue,*pLQueue;

//隊列初始化
void InitQueue(pLQueue Q)
{
	Q->front=(pQueue)malloc(sizeof(pQueue));
	if(NULL==Q->front)
		exit(-1);
	Q->rear=(pQueue)malloc(sizeof(pQueue));
	if(NULL==Q->rear)
		exit(-1);
	Q->front->next=NULL;
	Q->rear->next=NULL;
	Q->Max=0;
}
//進隊
void EnterQueue(pLQueue Q,type data)
{
	pQueue p=(pQueue)malloc(sizeof(pQueue));
	if(NULL==p)
		exit(-1);
	p->data=data;
	p->next=NULL;
	if(NULL==Q->rear->next)//空隊列
	{
		Q->front->next=p;
		Q->rear->next=p;
	}
	else
	{
		Q->rear->next->next=p;
		Q->rear->next=p;
	}
	if(data>Q->Max)
		Q->Max=data;
}
//出隊
pQueue DeleteQueue(pLQueue Q)
{
	if(NULL==Q->rear->next)
		exit(-1);
     
	if(NULL==Q->front->next->next)//只有一個元素
	{
	  Q->rear->next=NULL;
	}
	 pQueue temp=Q->front->next;
	 Q->front->next=temp->next;
	 return temp;
}

int _tmain(int argc, _TCHAR* argv[])
{
	type a[6]={21,24,11,16,19,150};
	lqueue Q;
	InitQueue(&Q);
	for(int i=0;i<6;i++)
		EnterQueue(&Q,a[i]);
	
	pLQueue L=&Q;
	cout<<L->Max<<endl;
	
	pQueue temp=DeleteQueue(&Q);
	cout<<"出隊元素爲:"<<temp->data<<endl;
	return 0;
}

結果爲:


發佈了62 篇原創文章 · 獲贊 23 · 訪問量 11萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章