1. 程式人生 > >連結串列實現佇列的出隊和入隊,棧的入棧和出棧

連結串列實現佇列的出隊和入隊,棧的入棧和出棧

佇列的出隊和入隊

queue.h

#ifndef QUEUE_H_
#define QUEUE_H_
#include<iostream>

typedef struct tagstudent{
	int data;
	struct tagstudent *next;
}node;

typedef struct tagqueue{
	node *first;//佇列頭指標,指向連結串列的第一個節點
	node *rear;
}queue;

class Cqueue{
public:
	Cqueue(){
	}
	~Cqueue(){
	}
	queue *push_queue(queue *HQ, int x);
	queue *pop_queue(queue *HQ);
	int    top_queue(queue *HQ);
private:
	queue *HQ;
};
#endif
queue.cpp
#include"queue.h"

queue * Cqueue:: push_queue(queue *HQ, int x)
{
	node *s;
	s = new node;
	s->data = x;
	s->next = NULL;

	if (HQ->rear == NULL)//queue is empty
	{
		HQ->first = s;
		HQ->rear = s;
	}
	else
	{
		HQ->rear->next = s;//將尾指標的next指向新增元素s
		HQ->rear = s;//將尾指標移動到新入隊的元素s
	}

	return HQ;
}
queue *Cqueue::pop_queue(queue *HQ)//只能把佇列第一個刪掉
{
	node *s; int x;
	if (HQ->first == NULL)
	{
		throw("空佇列");
	}
	else{
		s = HQ->first;
		x = HQ->first->data;
		if (HQ->first == HQ->rear)//佇列只有一個節點
		{
			HQ->first = NULL;
			HQ->rear = NULL;
		}
		else
		{
			HQ->first = HQ->first->next;
			delete s;
		}
	}
	return HQ;
}

int Cqueue::top_queue(queue *HQ)
{
	if (HQ->first != NULL)
	{
		return HQ->first->data;
	}
	else
		throw("佇列為空");
}

棧的出棧和入棧

stack.h

#ifndef STACK_H_
#define STACK_H_
#include<iostream>

typedef struct tagstudent{
	int data;
	struct tagstudent *next;
}node;

typedef struct tagstack{
	node *stacklow;//棧底指標,指向連結串列第一個節點
	node *stacktop;//棧頂指標
}stack;

class Cstack{
public:
	Cstack(){
	}
	~Cstack(){
	}
	stack *push(stack *ST, int x);
	stack *pop(stack *ST);
	int    top(stack *ST);
private:
	Cstack *ST;
};

#endif

stack.cpp
#include"stack.h"
stack *Cstack::push(stack *ST,int x)
{
	node *s;
	s = new node;
	s->data = x;
	if (ST->stacklow == NULL)//空棧
	{
		ST->stacklow = s;
		ST->stacktop = s;
	}
	else
	{
		ST->stacktop->next = s;
		ST->stacktop = s;
	}
	return ST;
}
stack * Cstack::pop(stack *ST)
{
	node *s;
	if (ST->stacklow == NULL)
	{
		throw("空棧");
	}
	else
	{
		s = ST->stacklow;
		if (ST->stacklow == ST->stacktop)//只有一個節點
		{
			ST->stacklow = NULL;
			ST->stacktop = NULL;
		}
		else
		{
			while (s->next != ST->stacktop)
			{
				s = s->next;
			}
			ST->stacktop = s;
			ST->stacktop->next = NULL;
		}
		return ST;
	}
}
int Cstack::top(stack *ST)
{
	if (ST->stacklow != NULL)//棧不為空
	{
		return ST->stacktop->data;
	}
	else
		throw("棧為空");
}

總結:佇列先進先出,入隊就是單鏈表在尾節點插入,出隊就是刪除單鏈表頭結點。

               棧後進先出,入棧就是單鏈表在尾節點插入, 出棧就是刪除單鏈表尾節點,需要從頭結點進行遍歷,一直找到尾節點的前驅節點為止。