前端学习数据结构之【栈】
4.1Stack - Linked list based implementation
stack ADT:LIFO
Insert/delete
- at end of list(tail) O(n)
- at beginning(head) O(1)
//栈顶Push/Pop/delete
#include<stdio.h>
#include<stdib.h>
struct Node {
int data;
struct Node* link;
};
struct Node* top = NULL;
void Push(int x){
struct Node* temp = (struct Node*)malloc(sizeof(struct Node*));
temp->data = x;
temp->link = top;
top = temp;
}
void Pop(){
struct Node *temp;
if(top == NULL)return;
temp = top;
top = top->link;
free(temp);
}
- 用链表来实现栈有一些优点,和基于数组实现相比,不需要担心内存溢出问题,在需要的时候使用内存,不需要的时候释放内存。
4.2 Using stack to reverse
- reverse a string
- reverse a linked list
4.2.1reverse a string
#include<iostream>
#include<stack>//stack from standard template library(STL)
using namespace std;
// class Stack
// {
// private:
// char A[101];
// int top;
// public:
// void Push(int x);
// void Pop();
// int Top();
// bool IsEmpty();
// }
//------- time-complexity:O(n) space-complexity:O(n) 不好的算法
void Reverse(char *C, int n)
{
stack<char> S;
//loop for push
for(int i=0;i<n;i++){
S.push(C[i])
}
//loop for pop
for(int i=0;i<n;i++){S
C[i] = S.top();
S.pop();
}
}
//-----------time-complexity:O(n) space-complexity:O(n) 不好的算法
//-------------链表反向输出start
struck Node{
int data;
Node* next;
}
void Reverse(){
if(head == NULL)return;
stack<struct Node*> S;
Node* temp = head;
while(temp != NULL){
S.push(temp);
temp = temp->next;
}
temp = S.top();
head = temp;
S.pop();
while(!S.empty()){
temp->next = S.top();
S.pop();
temp = temp->next;
}
temp->next = NULL;
}
//-------------链表反向输出end
int main(){
char C[51];
printf("Enter a string");
gets(C);
Reverse(C,strlen(C));
printf("output = %s",C);
}
4.3 check for balanced parentheses
for(int i=0;i<n;i++){
if(exp[i] is '(' or '{' or '['){
push(exp[i]);
}else if (exp[i] is ')' or '}' or ']')
{
if(s is empty||top does notpair with exp[i]){
return false;
}else{
pop();
}
}
}
return s is empty?true:false;
4.4 Infix 中序算法 Postfix 后缀算法 Prefix 前缀算法 操作符
Evaluation of expressions
Infix Prefix Postfix
2+3 + 2 3 2 3 +
p-q -pq pq-
a+bc +abc abc*+
4.4.1 Evaluation of prefix and postfix expressions
2 3 * 5 4 * + 9 -
//自左向右的扫描
List:2,3 * = 6 so that is LIFO
6,5,4 *=6,20
6,20 + = 26
26,9 - = 17
EvaluatePostfix(exp){
create a stack S
for i<-0 to length(exp)-1
{
if(exp[i] is operand)
push(exp[i])
else if(exp[i] is operator)
{
op2<-pop()
op1<-pop()
res<-Perform(exp[i],op1,op2)
push(res)
}
}
return top of stack
}
-
-
- 2 3 * 5 4 9
//自右向左的扫描
- 2 3 * 5 4 9
-
4.4.2 Infix to Postfix
InfixToPostfix(exp){
create a stack S
rea<-empty string
for i<-0 to length(exp)-1
{
if exp[i] is operand
res<-res+exp[i]
else if exp[i] is operator
{
while(!S.empty() && HasHigherPrec(S.top(),exp[i]))
{
res<- res + S.top()
S.pop()
}
S.push(exp[i])
}
}
while(!S.empty())
{
res<-res + S.top()
S.pop()
}
return res
}