码迷,mamicode.com
首页 > 其他好文 > 详细

队列的链式存储(时间复杂度最小)

时间:2015-04-17 18:18:01      阅读:330      评论:0      收藏:0      [点我收藏+]

标签:

/*
 * 2015年4月17日14:04:56
 * 目的:用链式存储来实现队列
 * 这里我最开始想使用单链表来实现
 * 大家来想一下啊,其实单链表实现不是特别好
 * 因为虽然出队列的时间复杂度就是O(1),但是
 * 入队列的时间复杂度却是O(n),因为每次都是从末尾进行插入
 * 从末尾插入你首先就要找到当前指向尾指针的结点,由于链表是单向的
 * 所以必须从front开始进行遍历才能找到rear前一个结点。
 * 为了解决入队列这个时间复杂度的问题,我觉得可以使用双向链表来解决
 * 虽然这样会浪费一些内存空间,但是可以解决时间复杂度的问题。
*/

# include <stdio.h>

struct LinkNode{
	int data;
	LinkNode *next; 
	LinkNode *prior;
};

struct LinkQueue{
	LinkNode *front;//队头指针
	LinkNode *rear; //队尾指针
};

//定义一个int变量,表示队列的长度
int length = 0;

void initQueue(LinkQueue *queue)
{
	queue->front = new LinkNode; //这个相当于链表的头指针。
	queue->rear = new LinkNode; //相当于链表的尾指针。
	queue->front->next = queue->rear;
	queue->front->prior = NULL;
	queue->rear->next = NULL;
	queue->rear->prior = queue->front;
}

//判断队列是否为空
bool isEmpty(LinkQueue *queue)
{
	/*
	 * 其实判断为空还可以用queue->front == queue->rear == NULL
	 * 来判断,但是既然我这里设置了length全局变量,就想要好好利用
	*/

	if(length == 0)
		return true;
	else
		return false;
}

//进队列
void enterQueue(LinkQueue *queue,int value)
{
	LinkNode *temp = new LinkNode;
	temp->data = value; //把想要插入的值赋给一个新的结点


	/*将结点插入到尾结点和尾结点前面的元素之间,时间复杂度是O(1)*/

	temp->next = queue->rear;
	temp->prior = queue->rear->prior;
	queue->rear->prior->next = temp;
	queue->rear->prior = temp;

	length++;

}

//出队列
void deleteQueue(LinkQueue *queue,int *value)
{
	*value = queue->front->next->data;
	
	//出队列是从头部开始出
	queue->front->next = queue->front->next->next;
	queue->front->next->prior = queue->front;

	length--;
}

//打印出队列中所有的元素
void printQueue(LinkQueue *queue)
{
	if(isEmpty(queue))
	{
		printf("队列中无元素。\n");
	}
	
	else
	{
		printf("队列中元素为:\n");
		LinkNode *temp = queue->front->next;
		for(int i = 1;i <= length;i++)
		{
			printf("%4d ",temp->data);
			if(i % 10 == 0)
			{
				printf("\n");
			}
			temp = temp->next;
		}
		printf("\n");
	}
	
}

int main(void)
{
	LinkQueue queue;
	initQueue(&queue);
	for(int i = 1;i <= 20;i++)
		enterQueue(&queue,i);
	printQueue(&queue);

	int value = 0;
	deleteQueue(&queue,&value);
	deleteQueue(&queue,&value);
	printQueue(&queue);
	return 0;
}

队列的链式存储(时间复杂度最小)

标签:

原文地址:http://blog.csdn.net/u011257298/article/details/45098707

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!