數據結構實驗3:C++實現順序棧類與鏈棧類


                                                                                          實驗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 附源代碼

順序棧代碼:

 1 // stdafx.h : include file for standard system include files,
 2 //  or project specific include files that are used frequently, but
 3 //      are changed infrequently
 4 //
 5 
 6 #if !defined(AFX_STDAFX_H__F1CE48FC_1D41_45D9_B60D_6D065D91DB10__INCLUDED_)
 7 #define AFX_STDAFX_H__F1CE48FC_1D41_45D9_B60D_6D065D91DB10__INCLUDED_
 8 
 9 #if _MSC_VER > 1000
10 #pragma once
11 #endif // _MSC_VER > 1000
12 
13 #include <stdc++.h>
14 
15 using namespace std;
16 
17 //typedef int elementType;
18 typedef double elementType;
19 typedef char elementType1;
20 const int maxLength = 1000 + 3;
21 
22 // TODO: reference additional headers your program requires here
23 
24 //{{AFX_INSERT_LOCATION}}
25 // Microsoft Visual C++ will insert additional declarations immediately before the previous line.
26 
27 #endif // !defined(AFX_STDAFX_H__F1CE48FC_1D41_45D9_B60D_6D065D91DB10__INCLUDED_)

 

 

 1 // SeqStack1.h: interface for the SeqStack class.
 2 //
 3 //////////////////////////////////////////////////////////////////////
 4 
 5 #if !defined(AFX_SEQSTACK1_H__55EE245C_A5F8_47D4_9510_B3BA6C85FF63__INCLUDED_)
 6 #define AFX_SEQSTACK1_H__55EE245C_A5F8_47D4_9510_B3BA6C85FF63__INCLUDED_
 7 
 8 #if _MSC_VER > 1000
 9 #pragma once
10 #endif // _MSC_VER > 1000
11 
12 #include "charSeqStack.h"
13 
14 //using elementType = double;
15 typedef double elementType;
16 class SeqStack  
17 {
18 public:
19     SeqStack();
20     virtual ~SeqStack();
21     bool stackEmpty();
22     bool stackFull();
23     bool getTop( elementType& value );
24     bool push( elementType value );
25     bool pop();
26     int length();
27     void displayStack();
28     int isp( elementType1 _operator );//棧內優先級
29     int icp( elementType1 _operator );//棧外優先級
30     charSeqStack css;
31     double doOperator( elementType value1, elementType value2, elementType1 _operator );
32     void calculate( charSeqStack& css1, charSeqStack& css2 );
33     friend ostream &operator<< (ostream &os, const SeqStack &a)
34     {
35         for (int i = 0; i < a.top + 1; i++)
36         {
37             if (a.top == -1)
38                 return os;
39             os << a.data[i];
40         }
41 
42         return os;
43     }
44 
45 private:
46     elementType data[maxLength];
47     int top;
48 };
49 
50 #endif // !defined(AFX_SEQSTACK1_H__55EE245C_A5F8_47D4_9510_B3BA6C85FF63__INCLUDED_)

 

  1 // SeqStack1.cpp: implementation of the SeqStack class.
  2 //
  3 //////////////////////////////////////////////////////////////////////
  4 
  5 #include "stdafx.h"
  6 #include "SeqStack1.h"
  7 #include <iostream>
  8 #include <iomanip>
  9 
 10 //////////////////////////////////////////////////////////////////////
 11 // Construction/Destruction
 12 //////////////////////////////////////////////////////////////////////
 13 using namespace std;
 14 SeqStack::SeqStack()
 15 {
 16     top = -1;
 17 }
 18 
 19 SeqStack::~SeqStack()
 20 {    
 21 }
 22 
 23 bool SeqStack::stackEmpty()
 24 {
 25     return top == -1;
 26 }
 27 
 28 bool SeqStack::stackFull()
 29 {
 30     return top == maxLength - 1;
 31 }
 32 
 33 bool SeqStack::getTop( elementType& value )
 34 {
 35     if( stackEmpty() )
 36     {
 37         cout << "???ив????????ив" << endl;
 38         return false;
 39     }
 40     value = data[top];
 41     return true;
 42 }
 43 
 44 bool SeqStack::push( elementType value )
 45 {
 46     if( stackFull() )
 47     {
 48         cout << "?и▓ив????ив" << endl;
 49         return false;
 50     }
 51     top ++;
 52     data[top] = value;
 53     return true;
 54 }
 55 
 56 bool SeqStack::pop()
 57 {
 58     if( stackEmpty() )
 59     {
 60         cout << "??ив????ив" << endl;
 61         return false;
 62     }
 63     top --;
 64     return true;
 65 }
 66 
 67 int SeqStack::length()
 68 {
 69     if( stackEmpty() )
 70     {
 71         cout << "??ив" << endl;
 72         return -1;
 73     }
 74     return top + 1;
 75 }
 76 
 77 void SeqStack::displayStack()
 78 {
 79     if( stackEmpty() )
 80     {
 81         cout << "??ив????ив" << endl;
 82         return;
 83     }
 84     int column = 0;
 85     for( int i = 0; i <= top; i ++ )
 86     {
 87         cout << setw(6) << setiosflags( ios::left ) << data[i];
 88         column ++;
 89         if( column % 10 == 0 )
 90             cout << endl;
 91     }
 92 }
 93 
 94 int SeqStack::isp( char _operator )
 95 {
 96     switch(_operator)
 97     {
 98     case '#' :
 99         return 0;
100         break;
101     case '(':
102         return 6;
103         break;
104     case '*':
105         return 5;
106         break;
107     case '/':
108         return 5;
109         break;
110     case '+':
111         return 3;
112         break;
113     case '-':
114         return 3;
115         break;
116     case ')':
117         return 1;
118         break;
119     }
120 
121     cerr << "Error in SeqStack::isp" << endl;
122     return -1;
123 }
124 
125 int SeqStack::icp( char _operator )
126 {
127     switch(_operator)
128     {
129     case '#' :
130         return 0;
131         break;
132     case '(':
133         return 1;
134         break;
135     case '*':
136         return 4;
137         break;
138     case '/':
139         return 4;
140         break;
141     case '+':
142         return 2;
143         break;
144     case '-':
145         return 2;
146         break;
147     case ')':
148         return 6;
149         break;
150     }
151 
152     cerr << "Error in SeqStack::icp" << endl;
153     return -1;
154 }
155 
156 double SeqStack::doOperator( elementType value1, elementType value2, elementType1 _operator )
157 {
158     switch(_operator)
159     {
160     case '+':
161         return value1 + value2;
162         break;
163     case '-':
164         return value1 - value2;
165         break;
166     case '*':
167         return value1 * value2;
168         break;
169     case '/':
170         if( fabs(value2) < 0.0001 )
171         {
172             cout << "Divided by 0!" << endl;
173             return -1000000;
174         }
175         else
176             return value1 / value2;
177         break;
178     }
179 
180     cerr << "Error in SeqStack::doOperator" << endl;
181     return -1;
182 }
183 
184 void SeqStack::calculate( charSeqStack& css1, charSeqStack& css2 )//?????? css2 ?им????????? css1 ?
185 {
186     char ch, ch1;
187     int i = 0, j = 0;
188     double a, b;
189     css2.pop();
190     css2.getTop(ch);
191     css2.pop();
192     
193     // when the top of css2 is not '#' or the top of css is not empty.
194     while( css1.topValue() != -1 || ch != '#' )
195     {
196         // when the top of css2 is a number, put it into ss1
197         if( isdigit(ch) )
198         {
199             push( (int)( ch - '0' ) );
200             css2.getTop(ch);
201             css2.pop();
202         }
203 
204         // when the top of css2 is not a number,
205         else
206         {
207             css1.getTop(ch1);
208             if (ch1 == ')' && ch == '(')
209             {
210                 css1.pop();
211                 css2.getTop(ch);
212                 css2.pop();
213                 continue;
214             }
215             if( isp(ch1) < icp(ch) )
216             {
217                 css1.push(ch);
218                 css2.getTop(ch);
219                 css2.pop();
220             }
221             else if( isp(ch1) >= icp(ch) )
222             {
223                 getTop(a);
224                 pop();
225                 getTop(b);
226                 pop();
227                 push( doOperator( a, b, ch1 ) );
228                 css1.pop();
229             }            
230         }
231 
232     }
233      
234 }

 

 1 // charSeqStack.h: interface for the charSeqStack class.
 2 //
 3 //////////////////////////////////////////////////////////////////////
 4 
 5 #if !defined(AFX_CHARSEQSTACK_H__A9958AD3_333A_41B4_B399_B6895C7AA8C5__INCLUDED_)
 6 #define AFX_CHARSEQSTACK_H__A9958AD3_333A_41B4_B399_B6895C7AA8C5__INCLUDED_
 7 
 8 #if _MSC_VER > 1000
 9 #pragma once
10 #endif // _MSC_VER > 1000
11 
12 #include <iostream>
13 using namespace std;
14 //using elementType1 = char;
15 typedef char elementType1;
16 //const int maxLength = 1000;
17 
18 class charSeqStack  
19 {
20 public:
21     charSeqStack();
22     virtual ~charSeqStack();
23     bool stackEmpty();
24     bool stackFull();
25     bool getTop( elementType1& value );
26     bool push( elementType1 value );
27     bool pop();
28     int length();
29     int topValue();
30     void displayStack();
31     friend ostream &operator<< (ostream &os, const charSeqStack &a)
32     {
33         for (int i = 0; i < a.top+2; i++)
34         {
35             if (a.top == -1)
36                 return os;
37             os << a.data[i];
38         }
39 
40         return os;
41     }
42 
43 private:
44     elementType1 data[maxLength];
45     int top;
46 };
47 
48 
49 #endif // !defined(AFX_CHARSEQSTACK_H__A9958AD3_333A_41B4_B399_B6895C7AA8C5__INCLUDED_)

 

  1 // charSeqStack.cpp: implementation of the charSeqStack class.
  2 //
  3 //////////////////////////////////////////////////////////////////////
  4 
  5 #include "stdafx.h"
  6 #include "charSeqStack.h"
  7 #include <iostream>
  8 #include <iomanip>
  9 
 10 using namespace std;
 11 //////////////////////////////////////////////////////////////////////
 12 // Construction/Destruction
 13 //////////////////////////////////////////////////////////////////////
 14 
 15 charSeqStack::charSeqStack()
 16 {
 17     top = -1;
 18 }
 19 
 20 charSeqStack::~charSeqStack()
 21 {
 22 
 23 }
 24 
 25 bool charSeqStack::stackEmpty()
 26 {
 27     return top == -1;
 28 }
 29 
 30 bool charSeqStack::stackFull()
 31 {
 32     return top == maxLength - 1;
 33 }
 34 
 35 bool charSeqStack::getTop( elementType1& value )
 36 {
 37     if( stackEmpty() )
 38     {
 39         value = '#';
 40         cout << "???ив????????ив" << endl;
 41         return false;
 42     }
 43     value = data[top];
 44     return true;
 45 }
 46 
 47 bool charSeqStack::push( elementType1 value )
 48 {
 49     if( stackFull() )
 50     {
 51         cout << "?и▓ив????ив" << endl;
 52         return false;
 53     }
 54     top ++;
 55     data[top] = value;
 56     return true;
 57 }
 58 
 59 bool charSeqStack::pop()
 60 {
 61     if( stackEmpty() )
 62     {
 63         cout << "??ив????ив" << endl;
 64         return false;
 65     }
 66     top --;
 67     return true;
 68 }
 69 
 70 int charSeqStack::length()
 71 {
 72     if( stackEmpty() )
 73     {
 74         cout << "??ив" << endl;
 75         return -1;
 76     }
 77     return top + 1;
 78 }
 79 
 80 void charSeqStack::displayStack()
 81 {
 82     if( stackEmpty() )
 83     {
 84         cout << "??ив????ив" << endl;
 85         return;
 86     }
 87     int column = 0;
 88     for( int i = 0; i <= top; i ++ )
 89     {
 90         cout << setw(6) << setiosflags( ios::left ) << data[i];
 91         column ++;
 92         if( column % 10 == 0 )
 93             cout << endl;
 94     }
 95 }
 96 
 97 int charSeqStack::topValue()
 98 {
 99     return top;
100 }

 

 1 // SeqStack.cpp : Defines the entry point for the console application.
 2 //
 3 
 4 #include "stdafx.h"
 5 #include "SeqStack1.h"
 6 #include <iostream>
 7 
 8 using namespace std;
 9 int main(int argc, char* argv[])
10 {
11     SeqStack ss1;
12     ss1.push(0);
13     charSeqStack css1, css2;
14     char Str[] = "#2+5*(2+3)*6/2-4#";
15     //12+5*(2+3)*6/2-4
16     //char Str[] = "#(1+(5-3)*2+9)/2#";
17     //char Str[] = "#(1+2)*3#";
18     //char Str[] = "#(1)#";
19     //char Str[] = "#1*2+3#";
20     //char Str[] = "#1+1#";
21     //char Str[] = "#1#";
22     for( int i = 0; Str[i] != '\0'; i ++ )
23         css2.push( Str[i] );
24 
25     cout << "Start Calculation." << endl;
26     cout << "expression:" << css2 << endl;
27     ss1.calculate( css1, css2 );
28     cout << "Calculation Done!" << endl;
29 
30     double x;
31     if( ss1.getTop(x) )
32         cout << x << endl;
33     cin.get();
34     return 0;
35 }

 

鏈棧代碼:

 1 // stdafx.h : include file for standard system include files,
 2 //  or project specific include files that are used frequently, but
 3 //      are changed infrequently
 4 //
 5 
 6 #if !defined(AFX_STDAFX_H__2FE69ABE_CC01_4962_8147_FD6E39302FE4__INCLUDED_)
 7 #define AFX_STDAFX_H__2FE69ABE_CC01_4962_8147_FD6E39302FE4__INCLUDED_
 8 
 9 #if _MSC_VER > 1000
10 #pragma once
11 #endif // _MSC_VER > 1000
12 
13 #include <stdc++.h>
14 
15 using namespace std;
16 
17 typedef double elementType;
18 typedef char elementType1;
19 
20 typedef struct node
21 {
22     elementType data;
23     struct node *link;
24 }LStack, *PStack;
25 
26 typedef struct Node
27 {
28     elementType1 data;
29     struct Node *link;
30 }CLStack, *CPStack;
31 
32 typedef long ll;
33 
34 // TODO: reference additional headers your program requires here
35 
36 //{{AFX_INSERT_LOCATION}}
37 // Microsoft Visual C++ will insert additional declarations immediately before the previous line.
38 
39 #endif // !defined(AFX_STDAFX_H__2FE69ABE_CC01_4962_8147_FD6E39302FE4__INCLUDED_)

 

 1 // linkedStack.h: interface for the linkedStack class.
 2 //
 3 //////////////////////////////////////////////////////////////////////
 4 
 5 #if !defined(AFX_LINKEDSTACK_H__54B665DE_2CE8_4329_AED9_95FEAAAAE128__INCLUDED_)
 6 #define AFX_LINKEDSTACK_H__54B665DE_2CE8_4329_AED9_95FEAAAAE128__INCLUDED_
 7 
 8 #if _MSC_VER > 1000
 9 #pragma once
10 #endif // _MSC_VER > 1000
11 
12 #include "charLinkedStack.h"
13 
14 class linkedStack  
15 {
16 public:
17     linkedStack();
18     virtual ~linkedStack();
19     bool stackEmpty();
20     //bool stackFull();
21     bool getTop( elementType& value );
22     bool push( elementType value );
23     bool pop();
24     int length();
25     void displayStack();
26     int isp( char  _operator );//棧內優先級
27     int icp( char _operator );//棧外優先級
28     double doOperator( elementType value1, elementType value2, char _operator );
29     void calculate( char* Str );
30     charLinkedStack cls;
31     bool isPopOrder();
32     bool judge(const elementType *sour, int s1, const elementType *dest, int s2 );
33     void linkedStack::printValidPopStackSequence( int n, elementType *A, int cur );
34     friend ostream &operator<< ( ostream &os, const linkedStack &a )
35     {
36         //for ( int i = 0; i < a.top + 1; i ++ )
37         //{
38         //    if (a.top == -1)
39         //        return os;
40         //    os << a.data[i];
41         //}
42         LStack *tmp = a.top;
43         int column = 0;
44         while( tmp->link )
45         {
46             //cout << tmp->data << " ";
47             if( tmp->link == NULL )
48                 return os;
49                 //break;
50             //os << tmp->data << " ";
51             os << setw(7) << setiosflags(ios::left) << tmp->data << " ";
52             column ++;
53             if( column % 10 == 0 )
54                 os << setw(7) << setiosflags(ios::left) << endl;
55             tmp = tmp->link;
56         }
57         os << endl;
58 
59         return os;
60     }
61 private:
62     LStack *top;
63     int len;
64 };
65 
66 #endif // !defined(AFX_LINKEDSTACK_H__54B665DE_2CE8_4329_AED9_95FEAAAAE128__INCLUDED_)

 

  1 // linkedStack.cpp: implementation of the linkedStack class.
  2 //
  3 //////////////////////////////////////////////////////////////////////
  4 
  5 #include "stdafx.h"
  6 #include "linkedStack.h"
  7 
  8 //////////////////////////////////////////////////////////////////////
  9 // Construction/Destruction
 10 //////////////////////////////////////////////////////////////////////
 11 
 12 linkedStack::linkedStack()
 13 {
 14     top = new LStack;
 15     if( !top )
 16     {
 17         cerr << "Space allocating falied!Error in linkedStack::linkedStack()!" << endl;
 18     }
 19     top->link = NULL;
 20     //top = NULL;
 21     len = 0;
 22 }
 23 
 24 linkedStack::~linkedStack()
 25 {
 26     /*
 27     LStack *tmp = top;
 28     while( tmp->link )
 29     {
 30         LStack *q = tmp;
 31 
 32         tmp = tmp->link;
 33         delete q;
 34         
 35         len --;
 36     }    
 37     tmp->link = NULL;
 38     */
 39     while(top)
 40     {
 41         LStack *q = top;
 42         top = top->link;
 43         delete q;
 44     }
 45     top = NULL;
 46 }
 47 
 48 bool linkedStack::stackEmpty()
 49 {
 50     //follow style is not suitable for the code
 51     //return top == NULL;
 52     return top->link == NULL;
 53 }
 54 
 55 bool linkedStack::getTop( elementType& value )
 56 {
 57     if( stackEmpty() )
 58     {
 59         cerr << "Stack is Empty!Error in linkedStack::getTop!" << endl;
 60         //value = -1;
 61         return false;
 62     }
 63     value = top->data;
 64     return false;
 65 }
 66 
 67 bool linkedStack::push( elementType value )
 68 {
 69     LStack *newNode = new LStack;
 70     if( !newNode )
 71     {
 72         cerr << "Space allocating falied!" << endl;
 73         return false;
 74     }
 75     newNode->data = value;
 76     newNode->link = top;
 77     top = newNode;
 78     len ++;
 79     return true;
 80 }
 81 
 82 bool linkedStack::pop()
 83 {
 84     if( stackEmpty() )
 85     {
 86         cerr << "Stack is empty!Error in linkedStack::pop()!" << endl;
 87         return false;
 88     }
 89     LStack *tmp = top;
 90     
 91     top = top->link;
 92     delete tmp;
 93     len --;
 94     return true;
 95 }
 96 
 97 int linkedStack::length()
 98 {
 99     if( stackEmpty() )
100     {
101         cerr << "Stack is empty!Error in linkedStack::length()" << endl;
102         return -1;
103     }
104     int cnt = 0;
105     LStack *tmp = top;
106     while( tmp->link )
107     {
108         tmp = tmp->link;
109         cnt ++;
110     }
111     return cnt;
112 }
113 
114 void linkedStack::displayStack()
115 {
116     if( stackEmpty() )
117     {
118         cerr << "Stack is empty!Error in linkedStack::displayStack()" << endl;
119         return;
120     }
121     LStack *tmp = top;
122     int column = 0;
123     while( tmp->link )
124     {
125         cout << setw(7) << setiosflags(ios::left) << tmp->data << " ";
126         //cout << tmp->data << " ";
127         column ++;
128         if( column % 10 == 0 )
129             cout << setw(7) << setiosflags(ios::left) << endl;
130         tmp = tmp->link;
131     }
132     cout << endl;
133 }
134 
135 int linkedStack::isp( char _operator )
136 {
137     switch(_operator)
138     {
139     case '#' :
140         return 0;
141         break;
142     case '(':
143         return 6;
144         break;
145     case '*':
146         return 5;
147         break;
148     case '/':
149         return 5;
150         break;
151     case '%':
152         return 5;
153         break;
154     case '+':
155         return 3;
156         break;
157     case '-':
158         return 3;
159         break;
160     case ')':
161         return 1;
162         break;
163     }
164 
165     cerr << "Error in SeqStack::isp" << endl;
166     return -1;
167 }
168 
169 int linkedStack::icp( char _operator )
170 {
171     switch(_operator)
172     {
173     case '#' :
174         return 0;
175         break;
176     case '(':
177         return 1;
178         break;
179     case '*':
180         return 4;
181         break;
182     case '/':
183         return 4;
184         break;
185     case '%':
186         return 4;
187         break;
188     case '+':
189         return 2;
190         break;
191     case '-':
192         return 2;
193         break;
194     case ')':
195         return 6;
196         break;
197     }
198 
199     cerr << "Error in SeqStack::icp" << endl;
200     return -1;
201 }
202 
203 double linkedStack::doOperator( elementType value1, elementType value2, char _operator )
204 {
205     switch(_operator)
206     {
207     case '+':
208         return value1 + value2;
209         break;
210     case '-':
211         return value1 - value2;
212         break;
213     case '*':
214         return value1 * value2;
215         break;
216     case '/':
217         if( fabs(value2) < 0.0001 )
218         {
219             cout << "Divided by 0!" << endl;
220             return -1000000;
221         }
222         else
223             return value1 / value2;
224         break;
225     case '%':
226         if( fabs(value2) < 0.0001 )
227         {
228             cout << "Divided by 0!" << endl;
229             return -1000000;
230         }
231         else
232             return (int)value1 % (int)value2;
233         break;
234         
235     }
236 
237     cerr << "Error in SeqStack::doOperator" << endl;
238     return -1;
239 }
240 
241 void linkedStack::calculate( char* Str )
242 {
243     charLinkedStack css1;
244     char ch1;
245     int i = 0;
246     double a, b;
247     
248     int level = 0;
249     int temp = 0;
250  
251     while ( Str[i] != '\0' )
252     {
253         i ++;
254     }
255     i = i - 2;
256     while( css1.topValue() != NULL || Str[i] != '#' )
257     {
258         char ch = Str[i];
259         if ( isdigit(ch) )
260         {
261             temp = temp + pow( 10, level ) * int( ch - '0' );
262             level ++;
263             i --;
264         }
265         else
266         {
267             if (level)
268             {
269                 push(temp);
270                 temp = 0;
271                 level = 0;
272             }
273             css1.getTop(ch1);
274             if ( ch1 == ')' && ch == '(' )
275             {
276                 css1.pop();
277                 i --;
278                 continue;
279             }
280             if ( isp(ch1) < icp(ch) )
281             {
282                 css1.push(ch);
283                 i --;
284             }
285             else if (isp(ch1) >= icp(ch))
286             {
287                 getTop(a);
288                 pop();
289                 getTop(b);
290                 pop();
291                 push( doOperator( a, b, ch1 ) );
292                 css1.pop();
293             }
294         }
295     }
296 
297     if (level)
298     {
299         push(temp);
300     }
301      
302 }
303 
304 bool linkedStack::isPopOrder()
305 {
306     /*
307     當序列遞增時,ok
308     當序列遞減時,且相差為1 ,ok
309     當序列遞減時,且相差大於1,但后續序列都遞減時,ok
310     當序列遞減時,且相差大於1,但后續序列非嚴格遞減時,no
311 
312     直到序列遞減大於1時,如果后續序列嚴格遞減,則ok,否則no。其他情況都ok。
313     */
314     if( stackEmpty() )
315     {
316         return true;
317     }
318     bool decrease = true, increase = true, D_valueThanOne = false, D_valueEqualOne = true;
319     elementType value1, value2;
320 
321     getTop(value1);
322     pop();
323     while( !stackEmpty() )//原序列遞增,彈棧序列遞減;原序列遞減,彈棧序列遞增
324     {
325         
326         getTop(value2);
327         //pop();
328         //if( value2 > value1 && value2 - value1 > 1 )
329         if( value1 > value2 && fabs( value2 - value1 ) > 1 )
330         {    
331             while( !stackEmpty() )
332             {
333                 if( value1 >= value2 )
334                 {
335                     cout << fabs( value2 - value1 ) << endl;
336                     value1 = value2;
337                     pop();
338                 }
339                 else
340                     return false;
341             }
342         }
343         else
344             pop();
345     }
346     return true;
347 
348 }
349  
350 bool linkedStack::judge(const elementType *sour, int s1, const elementType *dest, int s2 )        //不比更改兩個序列的內容,所以可加const修飾限定符
351 {
352      assert(sour);//斷言可防止NULL指針的傳入(避免傳入指針引起程序崩潰的問題)
353      assert(dest);
354     //stack<char> ss;//借助庫函數創建一個棧
355     linkedStack ss;
356     if (s1 != s2) //如果兩個序列不一樣長,自然是非法的序列
357         return false;
358  
359     ss.push(*sour++); //將首元素壓棧
360     while (*dest != 0)  
361     {
362  
363         if (ss.stackEmpty() && *sour != 0) //如果棧為空且入棧序列未結束,則不斷壓入元素
364             ss.push(*sour++);
365         double x;
366         ss.getTop(x);
367         while (*dest != x && *sour != 0) 
368         {
369             ss.push(*sour++);//如果出棧元素和棧頂元素不匹配則繼續壓入元素
370             ss.getTop(x);
371         }
372         ss.getTop(x);
373         if (*dest == x )  //如果兩者相等,將該元素彈出,且指針指向出棧序列的下一位置上
374         {
375             dest++;
376             ss.pop();
377             continue;
378         }
379         ss.getTop(x);
380         if (*sour == 0&& x != *dest)  //如果一直不相等,知道入棧序列結束仍為匹配上,說明出棧序列非法
381         {
382             return false;
383         }
384     }
385     return true;//否則序列合法
386 }
387 
388 void linkedStack::printValidPopStackSequence( int n, elementType *A, int cur )
389 {
390     ios::sync_with_stdio(false);
391     double B[8];
392     for( int i = 0; i < n; i ++ )
393         B[i] = i + 1;
394     B[n] =  0;
395     
396     if( cur == n )
397     {
398         A[n] = 0;
399         if( judge( B, n + 1, A, n + 1 ) )
400         {
401             for( int i = 0; i < n; i ++ )
402             {
403                 cout << A[i] << " ";
404             }
405             cout << endl;
406         }
407     }
408     else
409     {
410         for( int j = 1; j <= n; j ++ )
411         {
412             bool ok = true;
413         for( int k = 0; k < cur; k ++ )
414         {
415             if( A[k] == j )
416                 ok = false;
417         }
418         if(ok)
419         {
420             A[cur] = j;
421             printValidPopStackSequence( n, A, cur + 1 );
422         }
423    }
424     }
425 }

 

 1 // charLinkedStack.h: interface for the charLinkedStack class.
 2 //
 3 //////////////////////////////////////////////////////////////////////
 4 
 5 #if !defined(AFX_CHARLINKEDSTACK_H__CBB1096F_5E0D_4725_8583_A16EF4EA8502__INCLUDED_)
 6 #define AFX_CHARLINKEDSTACK_H__CBB1096F_5E0D_4725_8583_A16EF4EA8502__INCLUDED_
 7 
 8 #if _MSC_VER > 1000
 9 #pragma once
10 #endif // _MSC_VER > 1000
11 
12 class charLinkedStack  
13 {
14 public:
15     charLinkedStack();
16     virtual ~charLinkedStack();
17     bool stackEmpty();
18     //bool stackFull();
19     bool getTop( elementType1& value );
20     bool push( elementType1 value );
21     bool pop();
22     int length();
23     void displayStack();
24     CPStack topValue();
25     void decToHex( long value );
26     bool brancheMatch( char *Str );
27     bool charLinkedStack::judge(const char *sour, const char *dest);
28     friend ostream &operator<< ( ostream &os, const charLinkedStack &a )
29     {
30         //for ( int i = 0; i < a.top + 1; i ++ )
31         //{
32         //    if (a.top == -1)
33         //        return os;
34         //    os << a.data[i];
35         //}
36         CLStack *tmp = a.top;
37         int column = 0;
38         while( tmp->link )
39         {
40             //cout << tmp->data << " ";
41             if( tmp->link == NULL )
42                 return os;
43                 //break;
44             os << tmp->data;
45             //os << setw(7) << setiosflags(ios::left) << tmp->data << " ";
46             //column ++;
47             //if( column % 10 == 0 )
48                 //os << setw(7) << setiosflags(ios::left) << endl;
49             tmp = tmp->link;
50         }
51         os << endl;
52 
53         return os;
54     }
55 private:
56     CLStack *top;
57     int len;
58 
59 };
60 
61 #endif // !defined(AFX_CHARLINKEDSTACK_H__CBB1096F_5E0D_4725_8583_A16EF4EA8502__INCLUDED_)

 

  1 // charLinkedStack.cpp: implementation of the charLinkedStack class.
  2 //
  3 //////////////////////////////////////////////////////////////////////
  4 
  5 #include "stdafx.h"
  6 #include "charLinkedStack.h"
  7 
  8 //////////////////////////////////////////////////////////////////////
  9 // Construction/Destruction
 10 //////////////////////////////////////////////////////////////////////
 11 
 12 charLinkedStack::charLinkedStack()
 13 {
 14     top = new CLStack;
 15     if( !top )
 16     {
 17         cerr << "Space allocating falied!Error in linkedStack::linkedStack()!" << endl;
 18     }
 19     top->link = NULL;
 20     //top = NULL;
 21     len = 0;
 22 }
 23 
 24 charLinkedStack::~charLinkedStack()
 25 {
 26     while(top)
 27     {
 28         CLStack *q = top;
 29         top = top->link;
 30         delete q;
 31     }
 32     top = NULL;
 33 }
 34 
 35 bool charLinkedStack::stackEmpty()
 36 {
 37     //follow style is not suitable for the code
 38     //return top == NULL;
 39     return top->link == NULL;
 40 }
 41 
 42 bool charLinkedStack::getTop( elementType1& value )
 43 {
 44     if( stackEmpty() )
 45     {
 46         //cerr << "Stack is Empty!Error in linkedStack::getTop!" << endl;
 47         value = '#';
 48         return false;
 49     }
 50     value = top->data;
 51     return false;
 52 }
 53 
 54 bool charLinkedStack::push( elementType1 value )
 55 {
 56     CLStack *newNode = new CLStack;
 57     if( !newNode )
 58     {
 59         cerr << "Space allocating falied!" << endl;
 60         return false;
 61     }
 62     newNode->data = value;
 63     newNode->link = top;
 64     top = newNode;
 65     len ++;
 66     return true;
 67 }
 68 
 69 bool charLinkedStack::pop()
 70 {
 71     if( stackEmpty() )
 72     {
 73         cerr << "Stack is empty!Error in linkedStack::pop()!" << endl;
 74         return false;
 75     }
 76     CLStack *tmp = top;
 77     
 78     top = top->link;
 79     delete tmp;
 80     len --;
 81     return true;
 82 }
 83 
 84 int charLinkedStack::length()
 85 {
 86     if( stackEmpty() )
 87     {
 88         cerr << "Stack is empty!Error in linkedStack::length()" << endl;
 89         return -1;
 90     }
 91     int cnt = 0;
 92     CLStack *tmp = top;
 93     while( tmp->link )
 94     {
 95         tmp = tmp->link;
 96         cnt ++;
 97     }
 98     return cnt;
 99 }
100 
101 void charLinkedStack::displayStack()
102 {
103     if( stackEmpty() )
104     {
105         cerr << "Stack is empty!Error in linkedStack::displayStack()" << endl;
106         return;
107     }
108     CLStack *tmp = top;
109     int column = 0;
110     while( tmp->link )
111     {
112         cout << setw(7) << setiosflags(ios::left) << tmp->data << " ";
113         //cout << tmp->data << " ";
114         column ++;
115         if( column % 10 == 0 )
116             cout << setw(7) << setiosflags(ios::left) << endl;
117         tmp = tmp->link;
118     }
119     cout << endl;
120 }
121 
122 CPStack charLinkedStack::topValue()
123 {
124     return top->link;//write as "return top;" is not available
125 }
126 
127 void charLinkedStack::decToHex( ll value )
128 {
129     ll tmp = value;
130     while(tmp)
131     {
132         ll mod = tmp % 16;
133         if( mod <= 9 )
134         {
135             push( (char) ( mod + '0' ) );
136         }
137         else
138         {
139             switch(mod)
140             {
141             case 10:
142                 push('A');
143                 break;
144             case 11:
145                 push('B');
146                 break;
147             case 12:
148                 push('C');
149                 break;
150             case 13:
151                 push('D');
152                 break;
153             case 14:
154                 push('E');
155                 break;
156             case 15:
157                 push('F');
158                 break;
159             default:
160                 cerr << "Error in void charSeqStack::transfor()" << endl;
161                 break;
162             }
163         }
164         tmp /= 16;
165     }
166 }
167 
168 bool charLinkedStack::brancheMatch( char *Str )
169 {
170     
171     int i = 0;
172     char ch = Str[i];
173     elementType1 ch1 = NULL;
174     while( ch != '\0' )
175     {
176         if( ch == '(' || ch == '[' || ch == '{' )
177         {
178             push(ch);
179             
180         }
181         else if( ch == ')' || ch == ']' || ch == '}' )
182         {
183             //ch1 = NULL;
184             if( !stackEmpty() )
185             {
186                 //ch1 = NULL;
187                 getTop(ch1);
188                 //把下面這句話放到下面這個if判斷里面結果就正確了
189                 //pop();
190                 //cout << (*this) << endl;
191                 if( ( ch == ')' && ch1 == '(' ) || 
192                     ( ch == ']' && ch1 == '[' ) || ( ch == '}' && ch1 == '{' ) )
193                 {
194                     //ch = NULL;
195                     //ch1 = NULL;
196                     pop();
197                     //continue;
198                 }    //ch = Str[ ++ i ];
199                 
200                 else if( ( ch == ')' && ch1 != '(' ) || 
201                     ( ch == ']' && ch1 != '[' ) || ( ch == '}' && ch1 != '{' ) )
202                     return false;
203             }
204             
205             else //if( stackEmpty() && !ch1 )
206                 return false;
207         }
208         
209         ch = Str[ ++ i ];
210     }
211     if( stackEmpty() )
212     {
213         return true;
214     }
215     
216     while( !stackEmpty() )
217     {
218         pop();
219         
220     }
221     
222     return false;
223 }
224  
225 bool charLinkedStack::judge(const char *sour, const char *dest)        //不比更改兩個序列的內容,所以可加const修飾限定符
226 {
227      assert(sour);//斷言可防止NULL指針的傳入(避免傳入指針引起程序崩潰的問題)
228      assert(dest);
229     //stack<char> ss;//借助庫函數創建一個棧
230     charLinkedStack ss;
231     if (strlen(sour) != strlen(dest)) //如果兩個序列不一樣長,自然是非法的序列
232         return false;
233  
234     ss.push(*sour++); //將首元素壓棧
235     while (*dest != '\0')  
236     {
237  
238         if (ss.stackEmpty() && *sour != '\0') //如果棧為空且入棧序列未結束,則不斷壓入元素
239             ss.push(*sour++);
240         char x;
241         ss.getTop(x);
242         while (*dest != x && *sour != '\0') 
243         {
244             ss.push(*sour++);//如果出棧元素和棧頂元素不匹配則繼續壓入元素
245             ss.getTop(x);
246         }
247         ss.getTop(x);
248         if (*dest == x )  //如果兩者相等,將該元素彈出,且指針指向出棧序列的下一位置上
249         {
250             dest++;
251             ss.pop();
252             continue;
253         }
254         ss.getTop(x);
255         if (*sour == '\0'&& x != *dest)  //如果一直不相等,知道入棧序列結束仍為匹配上,說明出棧序列非法
256         {
257             return false;
258         }
259     }
260     return true;//否則序列合法
261 }

 

  1 // _LinkedStack.cpp : Defines the entry point for the console application.
  2 //
  3 
  4 #include "stdafx.h"
  5 #include "linkedStack.h"
  6 
  7 /*
  8 void test()
  9 {
 10     ios::sync_with_stdio(false);
 11     //freopen( "x1.in", "r", stdin );
 12     FILE *fp = fopen( "x1.in", "r" );
 13     //cout << "werfe" << endl;
 14     linkedStack LS1;
 15     charLinkedStack CLS1, CLS2;
 16     for( int i = 1; i <= 113; i ++ )
 17     {
 18         //LS1.push(i);
 19     }
 20     //cout << LS1 << endl;
 21     //LS1.displayStack();
 22 
 23     for( int j = 0; j <= 26; j ++ )
 24     {
 25         //CLS1.push( (char)( 'A' + j ) );
 26     }
 27     /*
 28     char Str[] = "#12+5*(2+3)*6/2-4#";
 29     LS1.calculate(Str);
 30     cout << LS1;
 31     ll n;
 32     //while( cin >> n )
 33     {
 34         cin >> n;
 35         CLS1.decToHex(n);
 36         cout << CLS1;
 37         //CLS1.~charLinkedStack();
 38     }
 39     
 40     char Str2[1000];
 41     while(1)
 42     {
 43         gets(Str2);
 44         if(CLS2.brancheMatch(Str2) )
 45             cout << "YES!" << endl;
 46         else
 47             cout << "NO!" << endl;
 48     }
 49     //cout << CLS1;
 50     //cout << LS1.length() << endl;
 51     //int x;
 52     //LS1.getTop(x);
 53     //cout << x << endl;
 54     //LS1.pop();
 55     //LS1.getTop(x);
 56     //cout << endl;
 57     cin.get();
 58 }
 59 */
 60 
 61 int main(int argc, char* argv[])
 62 {
 63     /*
 64     while(1)
 65     {
 66         test();
 67     }
 68     
 69     ios::sync_with_stdio(false);
 70     //freopen( "x1.in", "r", stdin );
 71     
 72     //freopen( "x1.out", "w", stdout );
 73     */
 74     //FILE *fp = fopen( "x1.in", "r" );
 75     /*
 76     //cout << "werfe" << endl;
 77     linkedStack LS1;
 78     charLinkedStack CLS1, CLS2;
 79     //for( int i = 1; i <= 113; i ++ )
 80     //{
 81         //LS1.push(i);
 82     //}
 83     //cout << LS1 << endl;
 84     //LS1.displayStack();
 85 
 86     //for( int j = 0; j <= 26; j ++ )
 87 //    {
 88         //CLS1.push( (char)( 'A' + j ) );
 89 //    }
 90     
 91     linkedStack LS1;
 92     char Str[] = "#12+5*(2+3)*6/2-4#", Str2[] = "#34456%3+100*5+3-100#";
 93     LS1.calculate(Str);
 94     for( int i = 1;  Str[i] != '#' && i < strlen(Str); i++ )
 95         cout << Str[i];
 96     cout << " = " << LS1;
 97     LS1.pop();
 98     LS1.calculate(Str2);
 99     for( i = 1;  Str2[i] != '#' && i < strlen(Str2); i++ )
100         cout << Str2[i];
101     cout << " = " << LS1;
102     
103     charLinkedStack CLS1;
104     ll n;
105     while( cin >> n )
106     {
107         //cin >> n;
108         CLS1.decToHex(n);
109         cout << CLS1;
110         while( !CLS1.stackEmpty() )
111             CLS1.pop();
112         //CLS1.~charLinkedStack();
113     }
114     
115     charLinkedStack CLS2;
116     char Str2[1000];
117     while( fgets( Str2, 1000, fp ) != NULL )
118     {
119         //gets(Str2);
120         if( CLS2.brancheMatch(Str2) )
121             cout << Str2 << " ---> legal!" << endl;
122         else
123             cout << Str2 << " ---> illegal!" << endl;
124     }
125     
126     linkedStack LS2;
127     
128     for( int i = 1; i <= 10; i ++ )
129     {
130         LS2.push(i);
131     }
132     
133     LS2.push(1.0);
134     LS2.push(4.0);
135     LS2.push(2.0);
136     LS2.push(3.0);
137     
138     cout << LS2 << endl;
139     if( LS2.isPopOrder() )
140         cout << " --- legal" <<endl;
141     else
142         cout << " --- illegal" << endl;
143     
144     linkedStack LS3;
145     elementType Arr1[] = { 1, 2, 3, 4 }, Arr2[5];//, Arr2[] = { 1, 4, 2, 3 };
146     //elementType Arr1[100], Arr2[100];
147 
148     int cnt = 0;
149     
150     while( cnt ++ < 24 )
151     {
152         //if( LS3.judgeIsLegal( Arr1, Arr2 ) )
153         for( int i = 0; i < 5; i ++ )
154             cin >> Arr2[i];
155         if( LS3.judge( Arr1, 5, Arr2, 5 ) )
156         {
157             cout << setw(2) << cnt << " : ";
158             for( int j = 0; j < 4; j ++ )
159                 cout << Arr2[j] << " ";
160             cout << " ---> legal!" << endl;
161         }
162         else
163         {
164             //cout << cnt << " ---> NO!" << endl;
165             cout << setw(2) << cnt << " : ";
166             for( int j = 0; j < 4; j ++ )
167                 cout << Arr2[j] << " ";
168             cout << " ---> illegal!" << endl;
169         }
170     }
171 
172     */
173     linkedStack  LS5;
174     elementType A[8];
175     cout << "The valid out-of-stack sequences of 1 to 7 are:" << endl;
176     LS5.printValidPopStackSequence( 7, A, 0 );
177 
178     /*
179     
180     charLinkedStack ss;
181     char Str[4];
182     int cnt = 0;
183     while( cnt ++ < 24 )
184     {
185         gets(Str);
186         cout << cnt << " : " << Str << " --- " << ss.judge( "abcd",Str ) << endl;
187     }
188     */
189     cin.get();
190     return 0;
191 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM