栈和队列面试题(C语言版)

1.判断出入栈的合法性

https://blog.csdn.net/Payshent/article/details/69951411

2.使用两个栈实现一个队列

思想:1.栈1中的所有数据弹到栈2中(栈2为空栈)

           2.再从栈2弹出所有数据,则可出现队列的效果

(默认压数据压到队列1中,从队列2出数据)

typedef struct Stack
{
	DataType _array[MAX_SIZE];          //数组
	DataType top;			    //栈顶
	int size;			    //容量
}Stack;
void StackInit(Stack* p)
{
	p->size = 0;
	p->top = -1;
}

void StackPush(Stack* p,DataType x)
{
	if (p->size < MAX_SIZE)
	{
		p->_array[++p->top] = x;
		p->size++;
	}
	else
	{
		printf("栈满\n");
	}
}
DataType StackPop(Stack* p)
{
	assert(p);
	p->top--;
	p->size--;
	return p->_array[p->top + 1];
}

void test1(Stack* s,Stack* s1)
{
	if (StackEmpty(s1) == 0)                          //判断s1是否为空
	{
		while (s->top >= 0)
		{
			s1->_array[++s1->top] = StackPop(s);        //s弹出一个元素,放在s1中
			s1->size++;
		}
		while (s1->top >= 0)
		{
			printf("%d ", s1->_array[s1->top--]);         //从s1弹出元素
		}
		printf("\n");
	}
	else
	{
		printf("%d ", s1->_array[s1->top--]);
	}
}

3.使用两个队列实现一个栈

思想:1.先将队列1中的元素压入到队列2中,在队列1中只剩一个元素,将剩下的一个元素弹出

           2.再将队列2中的元素压入队列1中,剩最后一个元素,弹出

           3.重复上述步骤,直到队列1中没有元素

(如果中途需要往进再压入元素,则压在非空的队列中)

typedef struct QueueNode
{
	DataType data;
	struct QueueNode* _next;
}QueueNode;
typedef	struct Queue
{
	QueueNode* _head;
	QueueNode* _tail;
}Queue;

Queue.c
void QueueInit(Queue* p)
{
	p->_head = p->_tail = NULL;
}

QueueNode* BuyNode(DataType x)
{
	QueueNode* newNode = (QueueNode*)malloc(sizeof(QueueNode));
	assert(newNode);
	newNode->data = x;
	newNode->_next = NULL;
	return newNode;
}
void QueuePush(Queue* p, DataType x)
{
	if (p->_head == NULL)
		p->_head = p->_tail = BuyNode(x);
	else
	{
		p->_tail->_next = BuyNode(x);
		p->_tail = p->_tail->_next;
	}
}
QueueNode* QueuePop(Queue* p)
{
	assert(p);
	QueueNode* flag = p->_head;
	p->_head = p->_head->_next;
	return flag;
}
void QueueDestory(Queue* p)
{
	while (p->_head)
	{
		QueueNode* del = p->_head;
		p->_head = p->_head->_next;
		free(del);
	}
}
void test1(Queue* p, Queue* p1)
{
	while (p->_head)
	{
		while (p->_head != p->_tail)                 //剩一个元素
		{
			QueuePush(p1, QueuePop(p)->data);      //将剩下的一个元素压入p1
		}
		printf("%d ", QueuePop(p)->data);
		while (p1->_head)
		{
			QueuePush(p, QueuePop(p1)->data);       //将p1的元素全部压入到p
		}
	}
	printf("\n");
}

4.一个数组实现两个栈

https://blog.csdn.net/zw_1510/article/details/51644230

void ShareStacktest3()                  //一个数组两个栈
{
	DataType arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
	Stack s1;
	Stack s2;
	int i = 0;
	int j = sizeof(arr) / sizeof(arr[0]) - 1;
	int capacity = j + 1;
	StackInit(&s1);
	StackInit(&s2);
	while (s1.size < 2)
	{
		if (s1.size < MAX_SIZE)
		{
			StackPush(&s1, arr[i]);
			i++;
		}
		else
		{
			printf("栈1满\n");
			break;
		}
	}
	Print(&s1);
	printf("\n");
	while (s2.size < 7)
	{
		if (s2.size < MAX_SIZE)
		{
			StackPush(&s2, arr[j]);
			j--;
		}
		else
		{
			printf("栈2满:\n");
			break;
		}
	}
	Print(&s2);
	printf("\n");
}

猜你喜欢

转载自blog.csdn.net/BOXING666/article/details/81668418
今日推荐