栈与队列面试题一

题目一:有效的括号

题目:给定一个只包括 ‘(’,’)’,’{’,’}’,’[’,’]’ 的字符串 s ,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。 左括号必须以正确的顺序闭合。
示例 1:
输入:s = “()” 输出:true 示例 2:
输入:s = “()[]{}” 输出:true 示例 3:
输入:s = “(]” 输出:false 示例 4:
输入:s = “([)]” 输出:false 示例 5:
输入:s = “{[]}” 输出:true

基本思路:

由于栈的数据元素遵守后进先出(Last In First Out)。
我们首先遍历字符串,遇到前括号直接入栈。遇到后括号,判断该后括号与栈顶的前括号是否匹配,
正常情况一:若不匹配则,返回false;
正常情况二:若匹配则删除栈顶元素,继续遍历字符串,直到字符串遍历完毕。如果遍历到栈为空
还是匹配的,则表明该字符串的括号匹配,返回true;
特殊情况一:当栈内没有任何元素时,碰到了右括号;此时就表明括号不匹配,直接返回false;
特殊情况二:当栈内还有元素但字符串遍历到'\0'时,此时说明还有前括号未匹配也不匹配,
直接返回false;
正常情况三:当字符串遍历完后,并且栈内为空,此时表明括号匹配成功,返回true;

方法一:运用stl中的栈写

代码如下:

 bool isValid(string s) 
    {
        stack<char>st;      //存储字符串的栈
        int i=0;            //下标
        bool flag=true;     //假定默认括号就是匹配的
        while(s[i]!='\0')
        {
            if(  (s[i]=='(')  ||  (s[i]=='{') || (s[i]=='['))
            {
                //碰到左括号全部压入栈
                st.push(s[i]);
                i++;
            }
            else
            {
                if(st.empty())      //如果栈为空,但是碰到了右括号,则表明括号不匹配
                {
                    flag=false;
                    return flag;
                }

                //不匹配的情况
                if(   (st.top()=='['&&s[i]!=']')
                ||(    st.top()=='('&&s[i]!=')') 
                ||(    st.top()=='{'&&s[i]!='}') )
                {
                    flag=false;
                    return flag;
                }
                //匹配就让它继续往后走,并把匹配的字符弹出栈
                else
                {
                    st.pop();
                    i++;
                }
            }
        }
        //如果栈内还有左括号,但是没有右括号了,则表明不匹配
        if(!st.empty())
        {
            flag=false;
            return flag;
        }
        return flag;
    }

方法二:实现一个栈再写

代码如下:

typedef char StackDataType;
typedef struct Stack
{
	StackDataType* _array;	//动态数组
	int _top;			//栈顶下标
	int	_capacity;		//容量大小
}stack;
//动态数组的初始化
void StackInit(stack* pst)
{
	assert(pst != NULL);
	pst->_array = (StackDataType*)malloc(sizeof(StackDataType) * 4);
	if (pst->_array == NULL)
	{
		printf("初始化失败\n");
		exit(-1);
	}
	pst->_capacity = 4;
	pst->_top = 0;
}

//销毁
void StackDestory(stack* pst)
{
	free(pst->_array);
	pst->_array = NULL;
	pst->_top = 0;
	pst->_capacity = 0;
}

//入栈
void StackPush(stack* pst, const StackDataType x)
{
	assert(pst != NULL);
	if (pst->_top == pst->_capacity)
	{
		pst->_capacity *= 2;	//扩充容量至原来的二倍
		StackDataType* temp = (StackDataType*)realloc(pst->_array, sizeof(StackDataType) * pst->_capacity);
		if (temp == NULL)	//如果扩容失败则退出程序
		{
			printf("扩容失败\n");
			exit(-1);
		}
		else
		{
			pst->_array = temp;
		}
	}

	pst->_array[pst->_top] = x;
	pst->_top++;
}

//出栈
void StackPop(stack* pst)
{
	assert(pst != NULL);
	assert(pst->_top > 0);
	--pst->_top;
}

//获取栈顶元素
StackDataType StackTop(stack* pst)
{
	assert(pst != NULL);
	assert(pst->_top > 0);
	return pst->_array[pst->_top - 1];
}

//判空
//返回true是空,返回false为非空
bool StackEmpty(stack* pst)
{
	assert(pst != NULL);
	if (pst->_top == 0)
	{
		return true;
	}
	return false;
}

bool isValid(char * s)
{
	stack st;
	StackInit(&st);
	bool temp;
	while(*s!='\0')
	{
		if(*s=='('||*s=='['||*s=='{')
		{
			StackPush(&st,*s);
		}
		else
		{
			if(StackEmpty(&st))
			{
				temp=false;
				break;
			}
			char top=StackTop(&st);

			if(top!='['&&*s==']')
			{
				temp=false;
				break;
			}
			if(top!='('&&*s==')')
			{
				temp=false;
				break;
			}
			if(top!='{'&&*s=='}')
			{
				temp=false;
				break;
			}
			StackPop(&st);
		}
		s++;
	}
	if(*s=='\0')
	{
		temp=StackEmpty(&st);
	}
	//把栈销毁掉,不然会造成内存泄漏
	StackDestory(&st);
	return temp;

}

题目二:用队列实现栈

题目:请你仅使用两个队列实现一个后入先出(LIFO)的栈,并支持普通队列的全部四种操作(push、top、pop 和 empty)。
实现 MyStack 类:
void push(int x) 将元素 x 压入栈顶。
int pop() 移除并返回栈顶元素。
int top() 返回栈顶元素。
boolean empty() 如果栈是空的,返回 true ;否则,返回 false 。
注意:
你只能使用队列的基本操作 —— 也就是 push to back、peek/pop from front、size 和 is empty 这些操作。
你所使用的语言也许不支持队列。 你可以使用 list (列表)或者 deque(双端队列)来模拟一个队列 , 只要是标准的队列操作即可。

基本思路:

入栈操作时,首先将元素入队到queue 2 ,然后将queue 1的全部元素依次出队并入队到queue2,此时queue 2的前端的元素即为新入栈的元素,再将queue 1 和 queue 2互换,queue 1 的元素即为栈内的元素,queue 1 的前端和后端分别对应栈顶和栈底。

在这里插入图片描述

方法一:运用stl中的两个队列实现栈

代码如下:

class MyStack {
public:
	// Initialize your data structure here. 
	queue<int>q1;	
	queue<int>q2;
	//默认构造函数
	MyStack()
	{}

	// Push element x onto stack.
	void push(int x)
	{
		q2.push(x);
		while (!q1.empty())
		{
			//把q1队头的元素插入到q2的队尾
			q2.push(q1.front());
			q1.pop();
		}
		//运用全局函数swap来交换两个队列
		swap(q1, q2);
	}

	// Removes the element on top of the stack and returns that element.
	int pop()
	{
		//先获取队头的元素的值,在pop掉队头元素
		int cur = q1.front();
		q1.pop();
		return cur;
	}

	// Get the top element. 
	int top()
	{
		return q1.front();
	}

	// Returns whether the stack is empty. 
	bool empty()
	{
		return q1.empty();
	}
};

方法二:实现队列再模拟成栈

这里的思路与上面所写略有不同,但总体思想并没有改变。 队列的机制是先入先出,而栈的机制是先入后出。使用两个队列,始终保持一个队列为空。当我们需要进行压栈操作时,将数据压入不为空的队列中(若两个都为空,则随便压入一个队列)。当需要进行出栈操作时,将不为空的队列中的数据导入空队列,仅留下一个数据,这时将这个数据返回并且删除即可。判断栈是否为空,即判断两个队列是否同时为空。
代码如下:

typedef int QueueDataType;
typedef struct QueueNode
{
	//数据域
	QueueDataType _data;

	struct QueueNode* _next;
}QueueNode;
typedef struct Queue
{
	//队头指针
	QueueNode* _head;

	//队尾指针
	QueueNode* _tail;
}Queue;
//初始化
void QueueInit(Queue* pQ)
{
	assert(pQ != NULL);
	pQ->_head = NULL;
	pQ->_tail = NULL;
}
//销毁
void QueueDestory(Queue* pQ)
{
	assert(NULL != pQ);

	while (NULL != pQ->_head)
	{
		QueueNode* next = pQ->_head->_next;
		free(pQ->_head);
		pQ->_head = next;
	}
	pQ->_head = NULL;
	pQ->_tail = NULL;
}
//入队
void QueuePush(Queue* pQ, const QueueDataType x)
{
	assert(NULL != pQ);
	//创建一个新的结点,并赋予值
	QueueNode* newNode = (QueueNode*)malloc(sizeof(QueueNode));
	if (newNode == NULL)
	{
		printf("分配空间失败\n");
		exit(-1);
	}
	else
	{
		newNode->_data = x;
		newNode->_next = NULL;
	}
	if (pQ->_head == NULL)
	{
		pQ->_head = pQ->_tail = newNode;
	}
	else
	{
		pQ->_tail->_next = newNode;
		pQ->_tail = newNode;
	}
}
//出队
void QueuePop(Queue* pQ)
{
	assert(pQ!=NULL);
	assert(pQ->_head != NULL);
	QueueNode* next = pQ->_head->_next;
	free(pQ->_head);
	pQ->_head= next;
	if (pQ->_head == NULL)
	{
		 pQ->_tail = NULL;
	}
}
//取队头元素
QueueDataType QueueFront(Queue* pQ)
{
	assert(pQ != NULL);
	assert(pQ->_head != NULL);
	return pQ->_head->_data;
}
//取队尾元素
QueueDataType QueueBack(Queue* pQ)
{
	assert(pQ != NULL);
	assert(pQ->_tail != NULL);
	return pQ->_tail->_data;
}
//判断队是否为空,true表示队为空,false表示队不空
bool QueueEmpty(Queue* pQ)
{
	assert(pQ != NULL);
	if (pQ->_head == NULL)
	{
		return true;
	}
	return false;
}
//队中元素得个数
int QueueSize(Queue* pQ)
{
	assert(pQ != NULL);
	QueueNode* cur = pQ->_head;
	int size = 0;
	while (cur!=NULL)
	{
		size++;
		cur = cur->_next;
	}
	return size;
}
typedef struct
{
	Queue _Q1;
	Queue _Q2;
} MyStack;
// Initialize your data structure here.
MyStack* myStackCreate()
{
	MyStack* st = (MyStack*)malloc(sizeof(MyStack));
	QueueInit(&st->_Q1);//初始化第一个队列
	QueueInit(&st->_Q2);//初始化第二个队列
	return st;
}
// Push element x onto stack. 
void myStackPush(MyStack* obj, int x)
{
	//数据压入非空的那个队列
	if (!QueueEmpty(&obj->_Q1))
	{
		QueuePush(&obj->_Q1, x);
	}
	else
	{
		QueuePush(&obj->_Q2, x);
	}
}
// Removes the element on top of the stack and returns that element.
int myStackPop(MyStack* obj)
{
	Queue* empty = &obj->_Q1;
	Queue* Noempty = &obj->_Q2;
	if (QueueEmpty(&obj->_Q2))
	{
		empty = &obj->_Q2;
		Noempty = &obj->_Q1;
	}
	while (QueueSize(Noempty) > 1)
	{
		QueuePush(empty, QueueFront(Noempty));
		QueuePop(Noempty);
	}
	int top = QueueFront(Noempty);
	QueuePop(Noempty);
	return top;
}
// Get the top element. 
int myStackTop(MyStack* obj)
{
	if (!QueueEmpty(&obj->_Q1))
	{
		return QueueBack(&obj->_Q1);
	}
	else
	{
		return QueueBack(&obj->_Q2);
	}
}

//Returns whether the stack is empty.
bool myStackEmpty(MyStack* obj)
{
	return QueueEmpty(&obj->_Q1) && QueueEmpty(&obj->_Q2);
}

void myStackFree(MyStack* obj)
{
	QueueDestory(&obj->_Q1);
	QueueDestory(&obj->_Q2);
	free(obj);
}

题目三:用栈实现队列

题目:请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(push、pop、peek、empty):
实现 MyQueue 类:
void push(int x) 将元素 x 推到队列的末尾
int pop() 从队列的开头移除并返回元素
int peek() 返回队列开头的元素
boolean empty() 如果队列为空,返回 true ;否则,返回 false

说明:
你只能使用标准的栈操作 —— 也就是只有 push to top, peek/pop from top, size, 和 is empty 操作是合法的。
你所使用的语言也许不支持栈。你可以使用 list 或者 deque(双端队列)来模拟一个栈,只要是标准的栈操作即可。

进阶:
你能否实现每个操作均摊时间复杂度为 O(1) 的队列?换句话说,执行 n 个操作的总时间复杂度为 O(n) ,即使其中一个操作可能花费较长时间。

示例:
输入:
[“MyQueue”, “push”, “push”, “peek”, “pop”, “empty”]
[[], [1], [2], [], [], []]
输出:
[null, null, null, 1, 1, false]
解释:
MyQueue myQueue = new MyQueue();
myQueue.push(1); // queue is: [1]
myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue)
myQueue.peek(); // return 1
myQueue.pop(); // return 1, queue is [2]
myQueue.empty(); // return false

基本思路:

>将一个栈当作输入栈,用于压入push 传入的数据;另一个栈当作输出栈,用于pop 和peek 操作。每次pop 或peek。时,若输出栈为空则将输入栈的全部数据依次弹出并压入输出栈,这样输出栈从栈顶往栈底的顺序就是队列从队首往队尾的顺序

在这里插入图片描述
代码如下:

方法一:运用stl中的两个栈来实现队列

class MyQueue
{
public:
    // Initialize your data structure here. 
    stack<int>_inSt;        //只作输入栈
    stack<int>_outSt;       //只作输出栈
    MyQueue()
    {

    }

    // Push element x to the back of queue.
    void push(int x)        //往输入栈中放元素
    {
        _inSt.push(x);
    }

    // Removes the element from in front of queue and returns that element. 
    int pop()
    {
        //如果输出栈中没有元素了,先看看输入栈中有没有元素,有就把输入栈的元素push到输出栈中
        //此时输出栈的top就是队头
        //元素从队头出
        if (_outSt.empty())
        {
            while (!_inSt.empty())
            {
                _outSt.push(_inSt.top());
                _inSt.pop();
            }
        }
        int cur = _outSt.top();
        _outSt.pop();
        return cur;

    }

    // Get the front element. 
    int peek()
    {
        //如果输出栈中没有元素了,先看看输入栈中有没有元素,有就把输入栈的元素push到输出栈中
        //此时输出栈的top就是队头
        if (_outSt.empty())
        {
            while (!_inSt.empty())
            {
                _outSt.push(_inSt.top());
                _inSt.pop();
            }
        }
        return _outSt.top();
    }

    //Returns whether the queue is empty.
    bool empty()
    {
        //两个为NULL才为空
        return _outSt.empty() && _inSt.empty();
    }
};

方法二:实现栈后再模拟成队

typedef int STDataType;//栈中存储的元素类型

typedef struct Stack
{
	STDataType* a;//栈
	int top;//栈顶
	int capacity;//容量,方便增容
}Stack;

//初始化栈
void StackInit(Stack* pst)
{
	assert(pst);

	pst->a = (STDataType*)malloc(sizeof(STDataType)* 4);//初始化栈可存储4个元素
	pst->top = 0;//初始时栈中无元素,栈顶为0
	pst->capacity = 4;//容量为4
}

//销毁栈
void StackDestroy(Stack* pst)
{
	assert(pst);

	free(pst->a);//释放栈
	pst->a = NULL;//及时置空
	pst->top = 0;//栈顶置0
	pst->capacity = 0;//容量置0
}

//入栈
void StackPush(Stack* pst, STDataType x)
{
	assert(pst);

	if (pst->top == pst->capacity)//栈已满,需扩容
	{
		STDataType* tmp = (STDataType*)realloc(pst->a, sizeof(STDataType)*pst->capacity * 2);
		if (tmp == NULL)
		{
			printf("realloc fail\n");
			exit(-1);
		}
		pst->a = tmp;
		pst->capacity *= 2;//栈容量扩大为原来的两倍
	}
	pst->a[pst->top] = x;//栈顶位置存放元素x
	pst->top++;//栈顶上移
}

//检测栈是否为空
bool StackEmpty(Stack* pst)
{
	assert(pst);

	return pst->top == 0;
}

//出栈
void StackPop(Stack* pst)
{
	assert(pst);
	assert(!StackEmpty(pst));//检测栈是否为空

	pst->top--;//栈顶下移
}

//获取栈顶元素
STDataType StackTop(Stack* pst)
{
	assert(pst);
	assert(!StackEmpty(pst));//检测栈是否为空

	return pst->a[pst->top - 1];//返回栈顶元素
}

//获取栈中有效元素个数
int StackSize(Stack* pst)
{
	assert(pst);

	return pst->top;//top的值便是栈中有效元素的个数
}
/*---以上代码是栈的基本功能实现,以下代码是题解主体部分---*/
typedef struct {
    Stack pushST;//插入数据时用的栈
    Stack popST;//删除数据时用的栈
} MyQueue;

/** Initialize your data structure here. */

MyQueue* myQueueCreate() {
    MyQueue* obj = (MyQueue*)malloc(sizeof(MyQueue));//申请一个队列类型
    StackInit(&obj->pushST);//初始化pushST
    StackInit(&obj->popST);//初始化popST

    return obj;
}

/** Push element x to the back of queue. */
void myQueuePush(MyQueue* obj, int x) {
    StackPush(&obj->pushST, x);//插入数据,向pushST插入
}

/** Get the front element. */
int myQueuePeek(MyQueue* obj) {
    if(StackEmpty(&obj->popST))//popST为空时,需先将pushST中数据导入popST
    {
        while(!StackEmpty(&obj->pushST))//将pushST数据全部导入popST
        {
            StackPush(&obj->popST, StackTop(&obj->pushST));
            StackPop(&obj->pushST);
        }
    }
    return StackTop(&obj->popST);//返回popST栈顶的元素
}

/** Removes the element from in front of queue and returns that element. */
int myQueuePop(MyQueue* obj) {
    int top = myQueuePeek(obj);
    StackPop(&obj->popST);//删除数据,删除popST中栈顶的元素
    return top;
}

/** Returns whether the queue is empty. */
bool myQueueEmpty(MyQueue* obj) {
    return StackEmpty(&obj->pushST)&&StackEmpty(&obj->popST);//两个栈均为空,则“队列”为空
}

void myQueueFree(MyQueue* obj) {
    //先释放两个栈,再释放队列的结构体类型
    StackDestroy(&obj->pushST);
    StackDestroy(&obj->popST);
    free(obj);
}

题目四:设计循环队列

题目:设计你的循环队列实现。 循环队列是一种线性数据结构,其操作表现基于 FIFO先进先出)原则并且队尾被连接在队首之后以形成一个循环。它也被称为“环形缓冲器”。循环队列的一个好处是我们可以利用这个队列之前用过的空间。在一个普通队列里,一旦一个队列满了,我们就不能插入下一个元素,即使在队列前面仍有空间。但是使用循环队列,我们能使用这些空间去存储新的值。
你的实现应该支持如下操作:
MyCircularQueue(k): 构造器,设置队列长度为 k 。
Front: 从队首获取元素。如果队列为空,返回 -1 。
Rear: 获取队尾元素。如果队列为空,返回 -1 。
enQueue(value): 向循环队列插入一个元素。如果成功插入则返回真。
deQueue(): 从循环队列中删除一个元素。如果成功删除则返回真。
isEmpty(): 检查循环队列是否为空。
isFull(): 检查循环队列是否已满。
示例:
MyCircularQueue circularQueue = new MyCircularQueue(3); // 设置长度为 3
circularQueue.enQueue(1); // 返回 true
circularQueue.enQueue(2); // 返回 true
circularQueue.enQueue(3); // 返回 true
circularQueue.enQueue(4); // 返回 false,队列已满
circularQueue.Rear(); // 返回 3
circularQueue.isFull(); // 返回 true
circularQueue.deQueue(); // 返回 true
circularQueue.enQueue(4); // 返回 true
circularQueue.Rear(); // 返回 4

基本思路:

1.永远空出一个位置,不存储数据
2.如果头和尾相等,则证明为空
3.如果头和尾的下一个相等,则证明已满

代码如下

typedef struct {
    int *array;         //
    int size;           //队列最多能存多少个数据
    int tail;           //尾(队尾数据的下一个)
    int front;          //头
} MyCircularQueue;
//本题思路
/*永远空出一个位置,不存储数据
如果头和尾相等,则证明为空
如果头和尾的下一个相等,则证明已满
*/
MyCircularQueue* myCircularQueueCreate(int k) 
{
    MyCircularQueue*obj=(MyCircularQueue*)malloc(sizeof(MyCircularQueue));
    obj->array=(int*)malloc(sizeof(int)*(k+1));
    obj->size=k;
    obj->tail=0;
    obj->front=0;
    return obj;
}

bool myCircularQueueIsEmpty(MyCircularQueue* obj) 
{
    //当头下标与尾下标相同时,则证明队列为空
    return obj->front==obj->tail;
}

bool myCircularQueueIsFull(MyCircularQueue* obj) 
{
    //判断尾的下一个是否等于头,相等则已满
    int temp=obj->tail+1;
    //特殊情况,当tail指向的是最后一个位置的下标,它+1,就会超过开辟的数组空间
    //要把它弄成环就要当它等于size+1的时候,让它等于0,这样相当于逻辑上的循环队列
    if(temp==obj->size+1)
    {
        temp=0;
    }
    return temp==obj->front;
}

bool myCircularQueueEnQueue(MyCircularQueue* obj, int value) 
{
    //首先先判断是否已满,如果已满则返回false
    if(myCircularQueueIsFull(obj))
    {
        return false;
    }
    else
    {
        //把value赋给tail下标的位置
        obj->array[obj->tail]=value;
        obj->tail++;
        //当尾下标越界时,则需要我们要将它的下一个下标等于0,做逻辑上的循环队列
        if(obj->tail==obj->size+1)
        {
            obj->tail=0;
        }
        return true;
    }
}

bool myCircularQueueDeQueue(MyCircularQueue* obj)
{
    //首先先判断是否为空,如果为空则返回-1
    if(myCircularQueueIsEmpty(obj))
    {
        return false;
    }
    else
    {
        /*
        这里删除我们做逻辑上的删除,即front++即可
        但front一直自增会有可能发生越界的情况
        故当它等于size+1时,我们要将它的下一个下标等于0,做逻辑上的循环队列
        */
        obj->front++;
        if( obj->front==obj->size+1)
        {
            obj->front=0;
        }
        return true;
    }
}

int myCircularQueueFront(MyCircularQueue* obj) 
{
    //首先先判断是否为空,如果为空则返回-1
    if(myCircularQueueIsEmpty(obj))
    {
        return -1;
    }
    else
    {
        //如果不是空,就返回front所指下标的元素
        return obj->array[obj->front];
    }
}

int myCircularQueueRear(MyCircularQueue* obj) 
{
    //首先先判断是否为空,如果为空则返回-1
    if(myCircularQueueIsEmpty(obj))
    {
        return -1;
    }
    else
    {
        //此时这里我们还要处理一种特殊情况
        /*
        由于tail指向的并不是尾,而是队尾数据的下一个
        当tail等于0时,tail-1此时会越界,由于是要循环队列
        所以我们要把它的前一个就等于size下标的位置
        */
        int temp=obj->tail-1;
        if(temp==-1)
        {
            temp=obj->size;
        }
        return obj->array[temp];
    }
}

void myCircularQueueFree(MyCircularQueue* obj) 
{
    //释放malloc出来的空间
    free(obj->array);
    free(obj);
}

END...

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值