資料結構——棧的連結串列實現
棧的連結串列實現與陣列實現原理差不多,只要熟悉連結串列的操作就能快速寫出來。不過連結串列實現不需要考慮棧滿的問題,因為棧的大小完全由你壓棧決定。當然malloc申請的記憶體空間是有限的,超過了這個空間也不行。下面我講一些建立空棧,壓棧,出棧操作。
1、建立空棧
首先考慮,棧頂指標壓棧的時候到底是往連結串列下端增加,還是往上增加。若往下增長,那麼在出棧的時候,就無法實現,因為棧頂指標指向的是尾結點,單向連結串列是不能訪問上一個結點的,除非是雙向連結串列。為方便壓棧、出棧的操作,所以建立帶有頭結點的空棧。
/*
** 建立帶有頭結點的空棧
*/
Stack Create_Stack()
{
Stack S = (Stack) malloc(sizeof(struct SNode));
S->next = NULL;
return S;
}
2、壓棧
壓棧操作,實際上是將新結點插入到棧頂下方。
void Push(Stack S, int X)
{
Stack T = (Stack)malloc(sizeof(struct SNode));
T->Data = X;
T->next = S->next; /* 棧頂頭結點S想上移動 */
S->next = T;
}
3、出棧
出棧操作,實際上是刪除棧頂下方結點。
/*
** 出棧
*/
int Pop(Stack S)
{
Stack t = S->next;
int data ;
if(ISEmpty(S)) /* 棧空,返回0 */
{
printf("棧空\n");
return 0;
}
else{
S->next = t->next;
data = t->Data;
free(t);
t = NULL;
return data;
}
}
下面給出具體實現程式碼:
#include <stdio.h> #include <stdlib.h> typedef struct SNode *Stack; struct SNode{ int Data; Stack next; }; Stack Create_Stack(); int ISEmpty(Stack S); void Push(Stack S, int X); int Pop(Stack S); int main() { Stack S; int i; S = Create_Stack(); for(i=1; i<=10; i++) Push(S,i); for(; !ISEmpty(S); ) printf("%d\n",Pop(S)); } /* ** 建立帶有頭結點的空棧 */ Stack Create_Stack() { Stack S = (Stack) malloc(sizeof(struct SNode)); S->next = NULL; return S; } /* ** 判斷空棧 */ int ISEmpty(Stack S) { return (S->next == NULL); } /* ** 壓棧 */ void Push(Stack S, int X) { Stack T = (Stack)malloc(sizeof(struct SNode)); T->Data = X; T->next = S->next; /* 棧頂頭結點S想上移動 */ S->next = T; } /* ** 出棧 */ int Pop(Stack S) { Stack t = S->next; int data ; if(ISEmpty(S)) /* 棧空,返回0 */ { printf("棧空\n"); return 0; } else{ S->next = t->next; data = t->Data; free(t); t = NULL; return data; } }