1. 程式人生 > >棧和佇列面試題(C語言版)

棧和佇列面試題(C語言版)

1.判斷出入棧的合法性

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.一個數組實現兩個棧

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");
}