实验3 
3.1 实验目的

熟练掌握栈的顺序存储结构和链式存储结构。

熟练掌握栈的有关算法设计,并在顺序栈和链栈上实现。

根据具体给定的需求,合理设计并实现相关结构和算法。
3.2实验要求
3.2.1 顺序栈的实验要求

顺序栈结构和运算定义,算法的实现以库文件方式实现,不得在测试主程序中直接实现;

实验程序有较好可读性,各运算和变量的命名直观易懂,符合软件工程要求;

程序有适当的注释。
3.2.2 链栈实验要求

本次实验中的链栈结构指带头结点的单链表;

链栈结构和运算定义,算法的实现以库文件方式实现,不得在测试主程序中直接实现;

实验程序有较好可读性,各运算和变量的命名直观易懂,符合软件工程要求;

程序有适当的注释。
3.3 实验任务
3.3.1 顺序栈实验任务

设计并实现一个顺序栈,编写算法实现下列问题的求解。

<1>利用顺序栈实现将10进制数转换为16进制数。

第一组数据:4 / 4

第二组数据:11 / B

第三组数据:254 / FE

第四组数据:1357 / 54D

<2>对一个合法的数学表达式来说,其中的各大小括号“{”,“}”,“[”,“]”,“(”和“)”应是相互匹配的。设计算法对以字符串形式读入的表达式S,判断其中的各括号是否是匹配的。
3.3.2 链栈实验任务

以带头结点的单链表表示链栈,编写算法实现下列问题的求解。

<1>利用顺序栈实现将10进制数转换为16进制数。

第一组数据:4

第二组数据:11

第三组数据:254

第四组数据:1357

<2>对一个合法的数学表达式来说,其中的各大小括号“{”,“}”,“[”,“]”,“(”和“)”应是相互匹配的。设计算法对以字符串形式读入的表达式S,判断其中的各括号是否是匹配的。
3.4 选做题

非必做内容,有兴趣的同学选做。自行选择栈的存储结构。

<1>假设栈的输入序列为1、2、3、...、n,设计算法实现对给定的一个序列,判定其是否是此栈合法的输出序列。

<2>假设栈的输入序列为1、2、3、...、n,设计算法求出所有可能的出栈序列。

<3>利用栈求解算术表达式的值。
3.5 运行结果截图及说明

图1 顺序栈实现十进制转十六进制

图2 顺序栈解决表达式括号匹配问题(局部)

图3 顺序栈解决表达式括号匹配问题(局部)

图4 顺序栈解决表达式括号匹配问题(局部)

图5 顺序栈解决表达式括号匹配问题(局部)

图6 链栈实现十进制转十六进制

图7 链栈解决表达式括号匹配问题(局部)

图8 链栈解决表达式括号匹配问题(局部)

图9 链栈解决表达式括号匹配问题(局部)

图10 链栈解决表达式括号匹配问题(局部)

图11 链栈判断1、2、3、4排列中合法出栈序列的问题

图12 链栈解决输出1、2、3、4、5、6、7全排列中合法出栈序列的问题(放大可清晰观看)

图13 链栈中缀表达式求值问题

3.6 附源代码

顺序栈代码:

 // stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently, but
// are changed infrequently
// #if !defined(AFX_STDAFX_H__F1CE48FC_1D41_45D9_B60D_6D065D91DB10__INCLUDED_)
#define AFX_STDAFX_H__F1CE48FC_1D41_45D9_B60D_6D065D91DB10__INCLUDED_ #if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000 #include <stdc++.h> using namespace std; //typedef int elementType;
typedef double elementType;
typedef char elementType1;
const int maxLength = + ; // TODO: reference additional headers your program requires here //{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_STDAFX_H__F1CE48FC_1D41_45D9_B60D_6D065D91DB10__INCLUDED_)
 // SeqStack1.h: interface for the SeqStack class.
//
////////////////////////////////////////////////////////////////////// #if !defined(AFX_SEQSTACK1_H__55EE245C_A5F8_47D4_9510_B3BA6C85FF63__INCLUDED_)
#define AFX_SEQSTACK1_H__55EE245C_A5F8_47D4_9510_B3BA6C85FF63__INCLUDED_ #if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000 #include "charSeqStack.h" //using elementType = double;
typedef double elementType;
class SeqStack
{
public:
SeqStack();
virtual ~SeqStack();
bool stackEmpty();
bool stackFull();
bool getTop( elementType& value );
bool push( elementType value );
bool pop();
int length();
void displayStack();
int isp( elementType1 _operator );//栈内优先级
int icp( elementType1 _operator );//栈外优先级
charSeqStack css;
double doOperator( elementType value1, elementType value2, elementType1 _operator );
void calculate( charSeqStack& css1, charSeqStack& css2 );
friend ostream &operator<< (ostream &os, const SeqStack &a)
{
for (int i = ; i < a.top + ; i++)
{
if (a.top == -)
return os;
os << a.data[i];
} return os;
} private:
elementType data[maxLength];
int top;
}; #endif // !defined(AFX_SEQSTACK1_H__55EE245C_A5F8_47D4_9510_B3BA6C85FF63__INCLUDED_)
 // SeqStack1.cpp: implementation of the SeqStack class.
//
////////////////////////////////////////////////////////////////////// #include "stdafx.h"
#include "SeqStack1.h"
#include <iostream>
#include <iomanip> //////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
using namespace std;
SeqStack::SeqStack()
{
top = -;
} SeqStack::~SeqStack()
{
} bool SeqStack::stackEmpty()
{
return top == -;
} bool SeqStack::stackFull()
{
return top == maxLength - ;
} bool SeqStack::getTop( elementType& value )
{
if( stackEmpty() )
{
cout << "???ив????????ив" << endl;
return false;
}
value = data[top];
return true;
} bool SeqStack::push( elementType value )
{
if( stackFull() )
{
cout << "?и▓ив????ив" << endl;
return false;
}
top ++;
data[top] = value;
return true;
} bool SeqStack::pop()
{
if( stackEmpty() )
{
cout << "??ив????ив" << endl;
return false;
}
top --;
return true;
} int SeqStack::length()
{
if( stackEmpty() )
{
cout << "??ив" << endl;
return -;
}
return top + ;
} void SeqStack::displayStack()
{
if( stackEmpty() )
{
cout << "??ив????ив" << endl;
return;
}
int column = ;
for( int i = ; i <= top; i ++ )
{
cout << setw() << setiosflags( ios::left ) << data[i];
column ++;
if( column % == )
cout << endl;
}
} int SeqStack::isp( char _operator )
{
switch(_operator)
{
case '#' :
return ;
break;
case '(':
return ;
break;
case '*':
return ;
break;
case '/':
return ;
break;
case '+':
return ;
break;
case '-':
return ;
break;
case ')':
return ;
break;
} cerr << "Error in SeqStack::isp" << endl;
return -;
} int SeqStack::icp( char _operator )
{
switch(_operator)
{
case '#' :
return ;
break;
case '(':
return ;
break;
case '*':
return ;
break;
case '/':
return ;
break;
case '+':
return ;
break;
case '-':
return ;
break;
case ')':
return ;
break;
} cerr << "Error in SeqStack::icp" << endl;
return -;
} double SeqStack::doOperator( elementType value1, elementType value2, elementType1 _operator )
{
switch(_operator)
{
case '+':
return value1 + value2;
break;
case '-':
return value1 - value2;
break;
case '*':
return value1 * value2;
break;
case '/':
if( fabs(value2) < 0.0001 )
{
cout << "Divided by 0!" << endl;
return -;
}
else
return value1 / value2;
break;
} cerr << "Error in SeqStack::doOperator" << endl;
return -;
} void SeqStack::calculate( charSeqStack& css1, charSeqStack& css2 )//?????? css2 ?им????????? css1 ?
{
char ch, ch1;
int i = , j = ;
double a, b;
css2.pop();
css2.getTop(ch);
css2.pop(); // when the top of css2 is not '#' or the top of css is not empty.
while( css1.topValue() != - || ch != '#' )
{
// when the top of css2 is a number, put it into ss1
if( isdigit(ch) )
{
push( (int)( ch - '' ) );
css2.getTop(ch);
css2.pop();
} // when the top of css2 is not a number,
else
{
css1.getTop(ch1);
if (ch1 == ')' && ch == '(')
{
css1.pop();
css2.getTop(ch);
css2.pop();
continue;
}
if( isp(ch1) < icp(ch) )
{
css1.push(ch);
css2.getTop(ch);
css2.pop();
}
else if( isp(ch1) >= icp(ch) )
{
getTop(a);
pop();
getTop(b);
pop();
push( doOperator( a, b, ch1 ) );
css1.pop();
}
} } }
 // charSeqStack.h: interface for the charSeqStack class.
//
////////////////////////////////////////////////////////////////////// #if !defined(AFX_CHARSEQSTACK_H__A9958AD3_333A_41B4_B399_B6895C7AA8C5__INCLUDED_)
#define AFX_CHARSEQSTACK_H__A9958AD3_333A_41B4_B399_B6895C7AA8C5__INCLUDED_ #if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000 #include <iostream>
using namespace std;
//using elementType1 = char;
typedef char elementType1;
//const int maxLength = 1000; class charSeqStack
{
public:
charSeqStack();
virtual ~charSeqStack();
bool stackEmpty();
bool stackFull();
bool getTop( elementType1& value );
bool push( elementType1 value );
bool pop();
int length();
int topValue();
void displayStack();
friend ostream &operator<< (ostream &os, const charSeqStack &a)
{
for (int i = ; i < a.top+; i++)
{
if (a.top == -)
return os;
os << a.data[i];
} return os;
} private:
elementType1 data[maxLength];
int top;
}; #endif // !defined(AFX_CHARSEQSTACK_H__A9958AD3_333A_41B4_B399_B6895C7AA8C5__INCLUDED_)
 // charSeqStack.cpp: implementation of the charSeqStack class.
//
////////////////////////////////////////////////////////////////////// #include "stdafx.h"
#include "charSeqStack.h"
#include <iostream>
#include <iomanip> using namespace std;
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
////////////////////////////////////////////////////////////////////// charSeqStack::charSeqStack()
{
top = -;
} charSeqStack::~charSeqStack()
{ } bool charSeqStack::stackEmpty()
{
return top == -;
} bool charSeqStack::stackFull()
{
return top == maxLength - ;
} bool charSeqStack::getTop( elementType1& value )
{
if( stackEmpty() )
{
value = '#';
cout << "???ив????????ив" << endl;
return false;
}
value = data[top];
return true;
} bool charSeqStack::push( elementType1 value )
{
if( stackFull() )
{
cout << "?и▓ив????ив" << endl;
return false;
}
top ++;
data[top] = value;
return true;
} bool charSeqStack::pop()
{
if( stackEmpty() )
{
cout << "??ив????ив" << endl;
return false;
}
top --;
return true;
} int charSeqStack::length()
{
if( stackEmpty() )
{
cout << "??ив" << endl;
return -;
}
return top + ;
} void charSeqStack::displayStack()
{
if( stackEmpty() )
{
cout << "??ив????ив" << endl;
return;
}
int column = ;
for( int i = ; i <= top; i ++ )
{
cout << setw() << setiosflags( ios::left ) << data[i];
column ++;
if( column % == )
cout << endl;
}
} int charSeqStack::topValue()
{
return top;
}
 // SeqStack.cpp : Defines the entry point for the console application.
// #include "stdafx.h"
#include "SeqStack1.h"
#include <iostream> using namespace std;
int main(int argc, char* argv[])
{
SeqStack ss1;
ss1.push();
charSeqStack css1, css2;
char Str[] = "#2+5*(2+3)*6/2-4#";
//12+5*(2+3)*6/2-4
//char Str[] = "#(1+(5-3)*2+9)/2#";
//char Str[] = "#(1+2)*3#";
//char Str[] = "#(1)#";
//char Str[] = "#1*2+3#";
//char Str[] = "#1+1#";
//char Str[] = "#1#";
for( int i = ; Str[i] != '\0'; i ++ )
css2.push( Str[i] ); cout << "Start Calculation." << endl;
cout << "expression:" << css2 << endl;
ss1.calculate( css1, css2 );
cout << "Calculation Done!" << endl; double x;
if( ss1.getTop(x) )
cout << x << endl;
cin.get();
return ;
}

链栈代码:

 // stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently, but
// are changed infrequently
// #if !defined(AFX_STDAFX_H__2FE69ABE_CC01_4962_8147_FD6E39302FE4__INCLUDED_)
#define AFX_STDAFX_H__2FE69ABE_CC01_4962_8147_FD6E39302FE4__INCLUDED_ #if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000 #include <stdc++.h> using namespace std; typedef double elementType;
typedef char elementType1; typedef struct node
{
elementType data;
struct node *link;
}LStack, *PStack; typedef struct Node
{
elementType1 data;
struct Node *link;
}CLStack, *CPStack; typedef long ll; // TODO: reference additional headers your program requires here //{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_STDAFX_H__2FE69ABE_CC01_4962_8147_FD6E39302FE4__INCLUDED_)
 // linkedStack.h: interface for the linkedStack class.
//
////////////////////////////////////////////////////////////////////// #if !defined(AFX_LINKEDSTACK_H__54B665DE_2CE8_4329_AED9_95FEAAAAE128__INCLUDED_)
#define AFX_LINKEDSTACK_H__54B665DE_2CE8_4329_AED9_95FEAAAAE128__INCLUDED_ #if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000 #include "charLinkedStack.h" class linkedStack
{
public:
linkedStack();
virtual ~linkedStack();
bool stackEmpty();
//bool stackFull();
bool getTop( elementType& value );
bool push( elementType value );
bool pop();
int length();
void displayStack();
int isp( char _operator );//栈内优先级
int icp( char _operator );//栈外优先级
double doOperator( elementType value1, elementType value2, char _operator );
void calculate( char* Str );
charLinkedStack cls;
bool isPopOrder();
bool judge(const elementType *sour, int s1, const elementType *dest, int s2 );
void linkedStack::printValidPopStackSequence( int n, elementType *A, int cur );
friend ostream &operator<< ( ostream &os, const linkedStack &a )
{
//for ( int i = 0; i < a.top + 1; i ++ )
//{
// if (a.top == -1)
// return os;
// os << a.data[i];
//}
LStack *tmp = a.top;
int column = ;
while( tmp->link )
{
//cout << tmp->data << " ";
if( tmp->link == NULL )
return os;
//break;
//os << tmp->data << " ";
os << setw() << setiosflags(ios::left) << tmp->data << " ";
column ++;
if( column % == )
os << setw() << setiosflags(ios::left) << endl;
tmp = tmp->link;
}
os << endl; return os;
}
private:
LStack *top;
int len;
}; #endif // !defined(AFX_LINKEDSTACK_H__54B665DE_2CE8_4329_AED9_95FEAAAAE128__INCLUDED_)
 // linkedStack.cpp: implementation of the linkedStack class.
//
////////////////////////////////////////////////////////////////////// #include "stdafx.h"
#include "linkedStack.h" //////////////////////////////////////////////////////////////////////
// Construction/Destruction
////////////////////////////////////////////////////////////////////// linkedStack::linkedStack()
{
top = new LStack;
if( !top )
{
cerr << "Space allocating falied!Error in linkedStack::linkedStack()!" << endl;
}
top->link = NULL;
//top = NULL;
len = ;
} linkedStack::~linkedStack()
{
/*
LStack *tmp = top;
while( tmp->link )
{
LStack *q = tmp; tmp = tmp->link;
delete q; len --;
}
tmp->link = NULL;
*/
while(top)
{
LStack *q = top;
top = top->link;
delete q;
}
top = NULL;
} bool linkedStack::stackEmpty()
{
//follow style is not suitable for the code
//return top == NULL;
return top->link == NULL;
} bool linkedStack::getTop( elementType& value )
{
if( stackEmpty() )
{
cerr << "Stack is Empty!Error in linkedStack::getTop!" << endl;
//value = -1;
return false;
}
value = top->data;
return false;
} bool linkedStack::push( elementType value )
{
LStack *newNode = new LStack;
if( !newNode )
{
cerr << "Space allocating falied!" << endl;
return false;
}
newNode->data = value;
newNode->link = top;
top = newNode;
len ++;
return true;
} bool linkedStack::pop()
{
if( stackEmpty() )
{
cerr << "Stack is empty!Error in linkedStack::pop()!" << endl;
return false;
}
LStack *tmp = top; top = top->link;
delete tmp;
len --;
return true;
} int linkedStack::length()
{
if( stackEmpty() )
{
cerr << "Stack is empty!Error in linkedStack::length()" << endl;
return -;
}
int cnt = ;
LStack *tmp = top;
while( tmp->link )
{
tmp = tmp->link;
cnt ++;
}
return cnt;
} void linkedStack::displayStack()
{
if( stackEmpty() )
{
cerr << "Stack is empty!Error in linkedStack::displayStack()" << endl;
return;
}
LStack *tmp = top;
int column = ;
while( tmp->link )
{
cout << setw() << setiosflags(ios::left) << tmp->data << " ";
//cout << tmp->data << " ";
column ++;
if( column % == )
cout << setw() << setiosflags(ios::left) << endl;
tmp = tmp->link;
}
cout << endl;
} int linkedStack::isp( char _operator )
{
switch(_operator)
{
case '#' :
return ;
break;
case '(':
return ;
break;
case '*':
return ;
break;
case '/':
return ;
break;
case '%':
return ;
break;
case '+':
return ;
break;
case '-':
return ;
break;
case ')':
return ;
break;
} cerr << "Error in SeqStack::isp" << endl;
return -;
} int linkedStack::icp( char _operator )
{
switch(_operator)
{
case '#' :
return ;
break;
case '(':
return ;
break;
case '*':
return ;
break;
case '/':
return ;
break;
case '%':
return ;
break;
case '+':
return ;
break;
case '-':
return ;
break;
case ')':
return ;
break;
} cerr << "Error in SeqStack::icp" << endl;
return -;
} double linkedStack::doOperator( elementType value1, elementType value2, char _operator )
{
switch(_operator)
{
case '+':
return value1 + value2;
break;
case '-':
return value1 - value2;
break;
case '*':
return value1 * value2;
break;
case '/':
if( fabs(value2) < 0.0001 )
{
cout << "Divided by 0!" << endl;
return -;
}
else
return value1 / value2;
break;
case '%':
if( fabs(value2) < 0.0001 )
{
cout << "Divided by 0!" << endl;
return -;
}
else
return (int)value1 % (int)value2;
break; } cerr << "Error in SeqStack::doOperator" << endl;
return -;
} void linkedStack::calculate( char* Str )
{
charLinkedStack css1;
char ch1;
int i = ;
double a, b; int level = ;
int temp = ; while ( Str[i] != '\0' )
{
i ++;
}
i = i - ;
while( css1.topValue() != NULL || Str[i] != '#' )
{
char ch = Str[i];
if ( isdigit(ch) )
{
temp = temp + pow( , level ) * int( ch - '' );
level ++;
i --;
}
else
{
if (level)
{
push(temp);
temp = ;
level = ;
}
css1.getTop(ch1);
if ( ch1 == ')' && ch == '(' )
{
css1.pop();
i --;
continue;
}
if ( isp(ch1) < icp(ch) )
{
css1.push(ch);
i --;
}
else if (isp(ch1) >= icp(ch))
{
getTop(a);
pop();
getTop(b);
pop();
push( doOperator( a, b, ch1 ) );
css1.pop();
}
}
} if (level)
{
push(temp);
} } bool linkedStack::isPopOrder()
{
/*
当序列递增时,ok
当序列递减时,且相差为1 ,ok
当序列递减时,且相差大于1,但后续序列都递减时,ok
当序列递减时,且相差大于1,但后续序列非严格递减时,no 直到序列递减大于1时,如果后续序列严格递减,则ok,否则no。其他情况都ok。
*/
if( stackEmpty() )
{
return true;
}
bool decrease = true, increase = true, D_valueThanOne = false, D_valueEqualOne = true;
elementType value1, value2; getTop(value1);
pop();
while( !stackEmpty() )//原序列递增,弹栈序列递减;原序列递减,弹栈序列递增
{ getTop(value2);
//pop();
//if( value2 > value1 && value2 - value1 > 1 )
if( value1 > value2 && fabs( value2 - value1 ) > )
{
while( !stackEmpty() )
{
if( value1 >= value2 )
{
cout << fabs( value2 - value1 ) << endl;
value1 = value2;
pop();
}
else
return false;
}
}
else
pop();
}
return true; } bool linkedStack::judge(const elementType *sour, int s1, const elementType *dest, int s2 ) //不比更改两个序列的内容,所以可加const修饰限定符
{
assert(sour);//断言可防止NULL指针的传入(避免传入指针引起程序崩溃的问题)
assert(dest);
//stack<char> ss;//借助库函数创建一个栈
linkedStack ss;
if (s1 != s2) //如果两个序列不一样长,自然是非法的序列
return false; ss.push(*sour++); //将首元素压栈
while (*dest != )
{ if (ss.stackEmpty() && *sour != ) //如果栈为空且入栈序列未结束,则不断压入元素
ss.push(*sour++);
double x;
ss.getTop(x);
while (*dest != x && *sour != )
{
ss.push(*sour++);//如果出栈元素和栈顶元素不匹配则继续压入元素
ss.getTop(x);
}
ss.getTop(x);
if (*dest == x ) //如果两者相等,将该元素弹出,且指针指向出栈序列的下一位置上
{
dest++;
ss.pop();
continue;
}
ss.getTop(x);
if (*sour == && x != *dest) //如果一直不相等,知道入栈序列结束仍为匹配上,说明出栈序列非法
{
return false;
}
}
return true;//否则序列合法
} void linkedStack::printValidPopStackSequence( int n, elementType *A, int cur )
{
ios::sync_with_stdio(false);
double B[];
for( int i = ; i < n; i ++ )
B[i] = i + ;
B[n] = ; if( cur == n )
{
A[n] = ;
if( judge( B, n + , A, n + ) )
{
for( int i = ; i < n; i ++ )
{
cout << A[i] << " ";
}
cout << endl;
}
}
else
{
for( int j = ; j <= n; j ++ )
{
bool ok = true;
for( int k = ; k < cur; k ++ )
{
if( A[k] == j )
ok = false;
}
if(ok)
{
A[cur] = j;
printValidPopStackSequence( n, A, cur + );
}
}
}
}
 // charLinkedStack.h: interface for the charLinkedStack class.
//
////////////////////////////////////////////////////////////////////// #if !defined(AFX_CHARLINKEDSTACK_H__CBB1096F_5E0D_4725_8583_A16EF4EA8502__INCLUDED_)
#define AFX_CHARLINKEDSTACK_H__CBB1096F_5E0D_4725_8583_A16EF4EA8502__INCLUDED_ #if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000 class charLinkedStack
{
public:
charLinkedStack();
virtual ~charLinkedStack();
bool stackEmpty();
//bool stackFull();
bool getTop( elementType1& value );
bool push( elementType1 value );
bool pop();
int length();
void displayStack();
CPStack topValue();
void decToHex( long value );
bool brancheMatch( char *Str );
bool charLinkedStack::judge(const char *sour, const char *dest);
friend ostream &operator<< ( ostream &os, const charLinkedStack &a )
{
//for ( int i = 0; i < a.top + 1; i ++ )
//{
// if (a.top == -1)
// return os;
// os << a.data[i];
//}
CLStack *tmp = a.top;
int column = ;
while( tmp->link )
{
//cout << tmp->data << " ";
if( tmp->link == NULL )
return os;
//break;
os << tmp->data;
//os << setw(7) << setiosflags(ios::left) << tmp->data << " ";
//column ++;
//if( column % 10 == 0 )
//os << setw(7) << setiosflags(ios::left) << endl;
tmp = tmp->link;
}
os << endl; return os;
}
private:
CLStack *top;
int len; }; #endif // !defined(AFX_CHARLINKEDSTACK_H__CBB1096F_5E0D_4725_8583_A16EF4EA8502__INCLUDED_)
 // charLinkedStack.cpp: implementation of the charLinkedStack class.
//
////////////////////////////////////////////////////////////////////// #include "stdafx.h"
#include "charLinkedStack.h" //////////////////////////////////////////////////////////////////////
// Construction/Destruction
////////////////////////////////////////////////////////////////////// charLinkedStack::charLinkedStack()
{
top = new CLStack;
if( !top )
{
cerr << "Space allocating falied!Error in linkedStack::linkedStack()!" << endl;
}
top->link = NULL;
//top = NULL;
len = ;
} charLinkedStack::~charLinkedStack()
{
while(top)
{
CLStack *q = top;
top = top->link;
delete q;
}
top = NULL;
} bool charLinkedStack::stackEmpty()
{
//follow style is not suitable for the code
//return top == NULL;
return top->link == NULL;
} bool charLinkedStack::getTop( elementType1& value )
{
if( stackEmpty() )
{
//cerr << "Stack is Empty!Error in linkedStack::getTop!" << endl;
value = '#';
return false;
}
value = top->data;
return false;
} bool charLinkedStack::push( elementType1 value )
{
CLStack *newNode = new CLStack;
if( !newNode )
{
cerr << "Space allocating falied!" << endl;
return false;
}
newNode->data = value;
newNode->link = top;
top = newNode;
len ++;
return true;
} bool charLinkedStack::pop()
{
if( stackEmpty() )
{
cerr << "Stack is empty!Error in linkedStack::pop()!" << endl;
return false;
}
CLStack *tmp = top; top = top->link;
delete tmp;
len --;
return true;
} int charLinkedStack::length()
{
if( stackEmpty() )
{
cerr << "Stack is empty!Error in linkedStack::length()" << endl;
return -;
}
int cnt = ;
CLStack *tmp = top;
while( tmp->link )
{
tmp = tmp->link;
cnt ++;
}
return cnt;
} void charLinkedStack::displayStack()
{
if( stackEmpty() )
{
cerr << "Stack is empty!Error in linkedStack::displayStack()" << endl;
return;
}
CLStack *tmp = top;
int column = ;
while( tmp->link )
{
cout << setw() << setiosflags(ios::left) << tmp->data << " ";
//cout << tmp->data << " ";
column ++;
if( column % == )
cout << setw() << setiosflags(ios::left) << endl;
tmp = tmp->link;
}
cout << endl;
} CPStack charLinkedStack::topValue()
{
return top->link;//write as "return top;" is not available
} void charLinkedStack::decToHex( ll value )
{
ll tmp = value;
while(tmp)
{
ll mod = tmp % ;
if( mod <= )
{
push( (char) ( mod + '' ) );
}
else
{
switch(mod)
{
case :
push('A');
break;
case :
push('B');
break;
case :
push('C');
break;
case :
push('D');
break;
case :
push('E');
break;
case :
push('F');
break;
default:
cerr << "Error in void charSeqStack::transfor()" << endl;
break;
}
}
tmp /= ;
}
} bool charLinkedStack::brancheMatch( char *Str )
{ int i = ;
char ch = Str[i];
elementType1 ch1 = NULL;
while( ch != '\0' )
{
if( ch == '(' || ch == '[' || ch == '{' )
{
push(ch); }
else if( ch == ')' || ch == ']' || ch == '}' )
{
//ch1 = NULL;
if( !stackEmpty() )
{
//ch1 = NULL;
getTop(ch1);
//把下面这句话放到下面这个if判断里面结果就正确了
//pop();
//cout << (*this) << endl;
if( ( ch == ')' && ch1 == '(' ) ||
( ch == ']' && ch1 == '[' ) || ( ch == '}' && ch1 == '{' ) )
{
//ch = NULL;
//ch1 = NULL;
pop();
//continue;
} //ch = Str[ ++ i ]; else if( ( ch == ')' && ch1 != '(' ) ||
( ch == ']' && ch1 != '[' ) || ( ch == '}' && ch1 != '{' ) )
return false;
} else //if( stackEmpty() && !ch1 )
return false;
} ch = Str[ ++ i ];
}
if( stackEmpty() )
{
return true;
} while( !stackEmpty() )
{
pop(); } return false;
} bool charLinkedStack::judge(const char *sour, const char *dest) //不比更改两个序列的内容,所以可加const修饰限定符
{
assert(sour);//断言可防止NULL指针的传入(避免传入指针引起程序崩溃的问题)
assert(dest);
//stack<char> ss;//借助库函数创建一个栈
charLinkedStack ss;
if (strlen(sour) != strlen(dest)) //如果两个序列不一样长,自然是非法的序列
return false; ss.push(*sour++); //将首元素压栈
while (*dest != '\0')
{ if (ss.stackEmpty() && *sour != '\0') //如果栈为空且入栈序列未结束,则不断压入元素
ss.push(*sour++);
char x;
ss.getTop(x);
while (*dest != x && *sour != '\0')
{
ss.push(*sour++);//如果出栈元素和栈顶元素不匹配则继续压入元素
ss.getTop(x);
}
ss.getTop(x);
if (*dest == x ) //如果两者相等,将该元素弹出,且指针指向出栈序列的下一位置上
{
dest++;
ss.pop();
continue;
}
ss.getTop(x);
if (*sour == '\0'&& x != *dest) //如果一直不相等,知道入栈序列结束仍为匹配上,说明出栈序列非法
{
return false;
}
}
return true;//否则序列合法
}
 // _LinkedStack.cpp : Defines the entry point for the console application.
// #include "stdafx.h"
#include "linkedStack.h" /*
void test()
{
ios::sync_with_stdio(false);
//freopen( "x1.in", "r", stdin );
FILE *fp = fopen( "x1.in", "r" );
//cout << "werfe" << endl;
linkedStack LS1;
charLinkedStack CLS1, CLS2;
for( int i = 1; i <= 113; i ++ )
{
//LS1.push(i);
}
//cout << LS1 << endl;
//LS1.displayStack(); for( int j = 0; j <= 26; j ++ )
{
//CLS1.push( (char)( 'A' + j ) );
}
/*
char Str[] = "#12+5*(2+3)*6/2-4#";
LS1.calculate(Str);
cout << LS1;
ll n;
//while( cin >> n )
{
cin >> n;
CLS1.decToHex(n);
cout << CLS1;
//CLS1.~charLinkedStack();
} char Str2[1000];
while(1)
{
gets(Str2);
if(CLS2.brancheMatch(Str2) )
cout << "YES!" << endl;
else
cout << "NO!" << endl;
}
//cout << CLS1;
//cout << LS1.length() << endl;
//int x;
//LS1.getTop(x);
//cout << x << endl;
//LS1.pop();
//LS1.getTop(x);
//cout << endl;
cin.get();
}
*/ int main(int argc, char* argv[])
{
/*
while(1)
{
test();
} ios::sync_with_stdio(false);
//freopen( "x1.in", "r", stdin ); //freopen( "x1.out", "w", stdout );
*/
//FILE *fp = fopen( "x1.in", "r" );
/*
//cout << "werfe" << endl;
linkedStack LS1;
charLinkedStack CLS1, CLS2;
//for( int i = 1; i <= 113; i ++ )
//{
//LS1.push(i);
//}
//cout << LS1 << endl;
//LS1.displayStack(); //for( int j = 0; j <= 26; j ++ )
// {
//CLS1.push( (char)( 'A' + j ) );
// } linkedStack LS1;
char Str[] = "#12+5*(2+3)*6/2-4#", Str2[] = "#34456%3+100*5+3-100#";
LS1.calculate(Str);
for( int i = 1; Str[i] != '#' && i < strlen(Str); i++ )
cout << Str[i];
cout << " = " << LS1;
LS1.pop();
LS1.calculate(Str2);
for( i = 1; Str2[i] != '#' && i < strlen(Str2); i++ )
cout << Str2[i];
cout << " = " << LS1; charLinkedStack CLS1;
ll n;
while( cin >> n )
{
//cin >> n;
CLS1.decToHex(n);
cout << CLS1;
while( !CLS1.stackEmpty() )
CLS1.pop();
//CLS1.~charLinkedStack();
} charLinkedStack CLS2;
char Str2[1000];
while( fgets( Str2, 1000, fp ) != NULL )
{
//gets(Str2);
if( CLS2.brancheMatch(Str2) )
cout << Str2 << " ---> legal!" << endl;
else
cout << Str2 << " ---> illegal!" << endl;
} linkedStack LS2; for( int i = 1; i <= 10; i ++ )
{
LS2.push(i);
} LS2.push(1.0);
LS2.push(4.0);
LS2.push(2.0);
LS2.push(3.0); cout << LS2 << endl;
if( LS2.isPopOrder() )
cout << " --- legal" <<endl;
else
cout << " --- illegal" << endl; linkedStack LS3;
elementType Arr1[] = { 1, 2, 3, 4 }, Arr2[5];//, Arr2[] = { 1, 4, 2, 3 };
//elementType Arr1[100], Arr2[100]; int cnt = 0; while( cnt ++ < 24 )
{
//if( LS3.judgeIsLegal( Arr1, Arr2 ) )
for( int i = 0; i < 5; i ++ )
cin >> Arr2[i];
if( LS3.judge( Arr1, 5, Arr2, 5 ) )
{
cout << setw(2) << cnt << " : ";
for( int j = 0; j < 4; j ++ )
cout << Arr2[j] << " ";
cout << " ---> legal!" << endl;
}
else
{
//cout << cnt << " ---> NO!" << endl;
cout << setw(2) << cnt << " : ";
for( int j = 0; j < 4; j ++ )
cout << Arr2[j] << " ";
cout << " ---> illegal!" << endl;
}
} */
linkedStack LS5;
elementType A[];
cout << "The valid out-of-stack sequences of 1 to 7 are:" << endl;
LS5.printValidPopStackSequence( , A, ); /* charLinkedStack ss;
char Str[4];
int cnt = 0;
while( cnt ++ < 24 )
{
gets(Str);
cout << cnt << " : " << Str << " --- " << ss.judge( "abcd",Str ) << endl;
}
*/
cin.get();
return ;
}

数据结构实验3:C++实现顺序栈类与链栈类的更多相关文章

  1. java与数据结构(6)---java实现链栈

    栈之链式存储结构链栈 链栈 栈的链式存储结构成为链栈.链栈是没有头结点,头结点就是栈顶指针top. 代码结构 package list; public interface Stackable;公共接口 ...

  2. 【C#】【数据结构】006-栈:链栈

    C#数据结构:链栈 1.自定义链栈结构: 链栈节点类 using System.Collections; using System.Collections.Generic; using UnityEn ...

  3. 数据结构 - 链栈的实行(C语言)

    数据结构-链栈的实现 1 链栈的定义 现在来看看栈的链式存储结构,简称为链栈. 想想看栈只是栈顶来做插入和删除操作,栈顶放在链表的头部还是尾部呢?由于单链表有头指针,而栈顶指针也是必须的,那干吗不让它 ...

  4. C语言实现链栈以及基本操作

    链栈,即用链表实现栈存储结构.链栈的实现思路同顺序栈类似,顺序栈是将数顺序表(数组)的一端作为栈底,另一端为栈顶:链栈也如此,通常我们将链表的头部作为栈顶,尾部作为栈底,如下下图所示: 将链表头部作为 ...

  5. 数据结构Java实现05----栈:顺序栈和链式堆栈

    一.堆栈的基本概念: 堆栈(也简称作栈)是一种特殊的线性表,堆栈的数据元素以及数据元素间的逻辑关系和线性表完全相同,其差别是线性表允许在任意位置进行插入和删除操作,而堆栈只允许在固定一端进行插入和删除 ...

  6. 数据结构Java实现03----栈:顺序栈和链式堆栈

    一.堆栈的基本概念: 堆栈(也简称作栈)是一种特殊的线性表,堆栈的数据元素以及数据元素间的逻辑关系和线性表完全相同,其差别是线性表允许在任意位置进行插入和删除操作,而堆栈只允许在固定一端进行插入和删除 ...

  7. SDUT-1479_数据结构实验之栈与队列九:行编辑器

    数据结构实验之栈与队列九:行编辑器 Time Limit: 1000 ms Memory Limit: 65536 KiB Problem Description 一个简单的行编辑程序的功能是:接受用 ...

  8. SDUT-3334_数据结构实验之栈与队列七:出栈序列判定

    数据结构实验之栈与队列七:出栈序列判定 Time Limit: 30 ms Memory Limit: 1000 KiB Problem Description 给一个初始的入栈序列,其次序即为元素的 ...

  9. SDUT-3332&3333_数据结构实验之栈与队列五:下一较大值

    数据结构实验之栈与队列六:下一较大值 Time Limit: 150 ms Memory Limit: 8000 KiB Problem Description 对于包含n(1<=n<=1 ...

随机推荐

  1. AtCoder Grand Contest 015 E - Mr.Aoki Incubator

    题目传送门:https://agc015.contest.atcoder.jp/tasks/agc015_e 题目大意: 数轴上有\(N\)个点,每个点初始时在位置\(X_i\),以\(V_i\)的速 ...

  2. Music in Car CodeForces - 746F

    Music in Car CodeForces - 746F 题意很难懂啊... 题意:http://blog.csdn.net/a838502647/article/details/74831793 ...

  3. 18.5.1使用Proxy和InvocationHandler创建动态代理

    package d18_5_1; public interface Person { void walk(); void sayHello(String name); } package d18_5_ ...

  4. canvas 平移&缩放

    1.平移 canvas其实只是一个包装器,真正起着重要作用的部分是2D渲染上下文,这才是我们真正绘制图形的地方. 然而2D渲染上下文是一种基于屏幕的标准绘制平台.它采用屏幕的笛卡尔坐标系统,以左上角( ...

  5. 一份最贴近真实面试的Java基础面试题

    这是一份Java基础知识的面试题.在网上的关于Java的面试题数不胜数,但认真看过感觉大多数都没有实用性,有很多是面试官根本就不会问到的,那些已经脱离了实际开发的技术问题.而这份资料来源自一份个人觉得 ...

  6. SQL中的笛卡儿积问题和多表连接操作

    (使用scott用户) SELECT * FROM scott.dept;--4SELECT * FROM scott.emp;--14 /**笛卡尔积内连接(等值连接)外连接(非等值连接)自连接*/ ...

  7. windows 查看某端口被占用情况

    百度经验 http://jingyan.baidu.com/article/3c48dd34491d47e10be358b8.html 基本命令 netstat -ano

  8. 为Qt添加SSL支持

    目标:为Qt添加SSL支持,使得应用可以发送HTTPS请求 环境:win7,Qt4.8.6 步骤: 1.到http://slproweb.com/products/Win32OpenSSL.html下 ...

  9. Summary of 2016 International Trusted Computing and Cloud Security Summit

    1)      Welcome Remarks 2)      The advancement of Cloud Computing and Tursted Computing national st ...

  10. CSS3实现单行、多行文本溢出(省略号的形式出现)

    <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...