Algorithm 棧和佇列

2022-05-26 12:36:15 字數 2876 閱讀 4479

一.棧和佇列綜合(演算法)

1.判斷單鏈表(帶頭結點)的結點值(字元型)是否中心對稱

1 bool issymmetry( linklist&l )

2 8 p = l->next;

9 for (i=0;i)

10 14 i--;

15 if ( len % 2)

16 p = p->next;

17 while ( top != -1)

18 24 return true;

25 }

2.共享棧由兩個順序棧s1,s2構成,總大小為100,請設計s1,s2入棧,出棧的演算法

1 #define maxsize 100

2 elemtype s[maxsize];

3 int top[2] = ;

4 bool push( inti, elemtype x )

5 12

13 bool pop( inti, elemtype x )

14

3.如果希望迴圈佇列中的元素都能得到利用,則需設定乙個標誌域tag,並以tag的值為0或1來區分隊頭指標front和隊尾rear相同時的佇列狀態是"空"還是"滿",編寫與此結構相應的入隊和出隊演算法

1 elemtype q[maxsize];

2 int front = -1, rear = -1;

3 // 隊空條件: front==rear&&tag==0

4 // 隊滿條件: front==rear&&tag==1

5 // 進隊操作: rear=(rear+1)%maxsize;

6 // q[rear]=x;

7 // tag=1;

8 // 出隊操作: front=(front+1)%maxsize;

9 // x=q[front];

10 // tag=0;

11 12 // 1)"tag"法迴圈隊列入隊演算法

13 boolenqueue( elemtype x )

14 22

23 // 2)"tag"法迴圈佇列出隊演算法

24 bool dequeue( elemtype&x )

25

4.q是乙個佇列,s是乙個空棧,實現將佇列中的元素逆置的演算法

1 elemtype s[maxsize], q[maxsize];

2 int top = -1, front = -1, rear = -1;

3 voidinverse(elemtype s, elemtype q)

4 11 while ( top != -1)

12 16 }

5.利用兩個棧s1,s2模擬乙個佇列,已知棧的4個運算如下:

1 // 已知:    

2 void push(stack&s, elemtype x);

3 void pop(stack& s, elemtype&x)

4 bool isempty(stack&s);

5 bool isoverflow( stack&s );

6 7 bool enqueue( stack& s1, stack&s2, elemtype x )

8 14 if ( !isempty( s2 ) )

15 return false;

16 while (!isempty(s1))

17 21 push( s1, x );

22 return true;

23 }

24 25 bool dequeue( stack& s1, stack& s2, elemtype&x )

26 31 if( isempty( s1 ) )

32 return false;

33 while (!isempty(s1))

34 38 pop( s2, x );

39 return true;

40 }

41 42 bool isempty( stack& s1, stack&s2 )

43

6.括號匹配問題:判別表示式中括號是否匹配(只含有$(),,\$)

1 bool isbracketmatch( char*str )

2 ':

24 c = s[top--];

25 if ( c != '

30 }

31 return top == -1;

32 }

7.利用棧實現以下遞迴函式的非遞迴計算:

$$p_(x)=

\cases(x)}-2(n-1)\cdot(x)} & n>1

}$$

1 double p( int n, doublex )

2 s[maxsize];

8 int top = -1, fv1 = 1, fv2 = 2 *x;

9 for ( int i = n; i > 1; i--)

10 s[++top].n =i;

11 while ( top != -1)

12 17 if ( n == 0 ) returnfv1;

18 returnfv2;

19 }

棧和佇列 單調佇列 單調棧

講解部落格鏈結 一 單調棧 1 什麼是單調棧?單調棧是指乙個棧內部元素具有嚴格單調性 單調遞增,單調遞減 的一種資料結構。2 單調棧的兩個性質 滿足從棧頂到棧底具有嚴格的單調性 滿足後進先出的特徵,越靠近棧底的元素越早的進棧。3 元素進棧的過程 對於當前進棧元素x 如果x 棧頂元素,x 進棧。否則 ...

棧和佇列 佇列

佇列 又一種特殊的線性表 佇列 queue 是只允許在一端進行插入,而在另一端進行刪除的運算受限的線性表 允許刪除的一端稱為隊頭 front 允許插入的一端稱為隊尾 rear 當佇列中沒有元素時稱為空佇列。佇列的修改是依先進先出的原則進行的。新來的成員總是加入隊尾 即不允許 加塞 每次離開的成員總是...

棧和佇列(佇列)

列隊類 public class myqueue 帶引數構造方法,引數為陣列大小 public myqueue int maxsize 新增資料 從隊尾插入 public void insert int value arr end value 注意是 end 不是end element 刪除資料,從...