棧學習筆記(二)

今天開始用c語言實現棧的基本操作。因爲沒有什麼模版可言,所以讓隊長給寫了一個代碼。把代碼貼出來,也算是自己的資料了。現在要做的就是研究一下代碼,然後自己寫出一個簡單的棧的代碼。

這是用c寫成的。

#include<iostream>
using namespace std;
struct mystack{
int a[6];
int pos;
}s;
void push(int elem)
{
	s.pos++;
	s.a[s.pos]=elem;
}
int top()
{
	return s.a[s.pos];
}
void pop()
{
	s.pos--;
}
int main()
{
	s.pos=-1;
	push(1);
	push(2);
	cout<<top()<<endl;
	pop();
	cout<<top()<<endl;
}
另外下面是另外一個同學寫的

#include<stdio.h>
struct Stack 
{
       char stack[10005];
       int top;
};

 void InitStack(Stack& a)
               
 {
        a.top=-1; 
 }
 void push(Stack& a,char item)
               
 {
           
        a.top++;
          
       a.stack[a.top]=item;
 }

void pop(Stack& a)
                
{
          
          
         a.top--;
         
}

int main()
{
	int a,b,c,n;
	char ch;
	scanf("%d",&n);
	getchar();
	while(n--)
	{
		Stack a;
		InitStack(a);
		while(scanf("%c",&ch)&&ch!='\n')
		{
			if(ch=='['||ch=='(')
				push(a,ch);
			else
			{
				if(a.stack[a.top]=='['&&ch==']')
				{	pop(a);}
				else if(a.stack[a.top]=='('&&ch==')')
	                pop(a);
				else
					push(a,ch);


			}
		}
		if(a.top==-1)
			printf("Yes\n");
		else
			printf("No\n");

	}
}

這兩段代碼很多地方都有相同之處。隊長寫的是int型的,下面的是char型的。

另外積累一個char型棧的模版。

#include<stdio.h>
struct Stack 
{
	char str[10005];
    int top;
};
void InitStack(Stack& a)               
{
        a.top=-1; 
}
void push(Stack& a,char item)              
{
	a.top++;
    a.str[a.top]=item;
}
void pop(Stack& a)                
{          
	a.top--;         
}



發佈了53 篇原創文章 · 獲贊 94 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章