學習的捷徑:多寫代碼
棧:棧是限制在一端進行插入操作和刪除操作的線性表,額,又是線性表,那就是說又可以有兩種儲存方式:順序棧,鏈式棧。允許進行操作的一端稱為“棧頂”,另一端稱為“棧底”。特點:先進先出。
所謂的棧和隊列,其實是一種技術,有時候需要特殊的儲存方式,然後在必要的時候還原該元素,就會利用到棧或者隊列,例如在ARM操作的一些裸機代碼中,需要保持狀態寄存器中的值,根據需要可以利用棧或者隊列來儲存,用起來很方便安全,所以在涉及到儲存資料之類的操作時候,要想到這兩個技術。
基本運算:
建立空棧:createstack();判斷是否空棧 isempty(S);判斷滿棧isfull(S);進棧:push(S,x);出棧pop(S);
同樣,再一次熟悉一下順序儲存和鏈式儲存
順序棧:
#include <stdio.h>#include <stdlib.h>#include <strings.h>#include <errno.h>#define N 10typedef int datatype;typedef struct { datatype data[N]; int top;}sqstack;sqstack * create(){ sqstack * s; bzero(&s,sizeof(s)); if((s = (sqstack *)malloc(sizeof(sqstack)))==NULL) { perror("malloc"); exit(-1); } s->top = -1; return s;}int isempty(sqstack *s){ if(s->top == -1) return 0; return -1;}int isfull(sqstack *s){ if(s->top == N-1) return 0; return -1;}int push(sqstack *s,datatype data){ if(isfull(s)==0) { printf("stack is full\n"); return -1; } s->top++; s->data[s->top] = data; return 0;}datatype pop(sqstack *s){ datatype data; if(isempty(s)==0) { printf("the sqstack is empty!"); return ; } data = s->data[s->top]; s->top--; return data;}void show(sqstack *s){ int i; i = s->top; if(isempty(s)==0) { printf("empty!"); return ; } printf("data = %d\n",s->data[i]); }int main(int argc,char * argv[]){ int i,ret; sqstack * s; s = create(); for(i = 1;i< 12;i++) { ret = push(s,i); if(ret != 0 ) return -1; show(s); } free(s); return 0;}
鏈式棧:
#include <stdio.h>#include <stdlib.h>typedef int datatype;typedef struct node{ datatype data; struct node * next;}linknode,*linkstack;linkstack create(){ linkstack h; if((h = (linkstack)malloc(sizeof(linknode)))==NULL) { perror("malloc"); return NULL; } h->next = NULL; return h;}int push(linkstack h,datatype data){ linkstack p; if((p = (linkstack)malloc(sizeof(linknode)))==NULL) { perror("malloc"); return -1; } p->data = data; p->next = h->next; h->next = p; return 0;}int isempty(linkstack h){ if(h->next==NULL) { printf("is empty\n"); return 1; } return 0;}datatype pop(linkstack h){ datatype data; linkstack p = NULL; if(isempty(h)) { return 0; } p = h->next; h->next = p->next; data = p->data; free(p); return data; }void show(linkstack h){ linkstack p = NULL; if(isempty(h)) { printf("is empty!\n"); return ; } p = h->next; while(p != NULL) { printf("data = %d\n",p->data); p = p->next; }}int main(int argc,char * argv[]){ int i; linkstack h; h = create(); for(i = 1;i < 10;i++) { push(h,i); } show(h); return 0;}
比較簡單的操作。接下來就是隊列了,一般用的迴圈隊列。一個有趣的程式叫做球鐘。
下次實現。