纯C语言实现链栈
#include <stdio.h>
#include <stdlib.h>typedef int ElemType;typedef struct StackNode{ElemType data;struct StackNode *next;
}StackNode;StackNode *InitStack(StackNode *S);//初始化
StackNode * DestroyStack(StackNode*S);//銷毀
void ClearStack(StackNode*S);//清空
int StackEmpty(StackNode*S);//判空
int StackLength(StackNode*S);//棧長度
ElemType GetTop(StackNode*S);//獲取棧頂元素,不修改指針位置
StackNode *Push(StackNode*S, ElemType e);//插入棧頂
StackNode *Pop(StackNode *S, ElemType *e);//刪除棧頂
void StackTraverse(StackNode *S);//從棧頂依次遍歷//初始化
StackNode *InitStack(StackNode *S){S = NULL;printf("初始化成功\n");return S;
}//銷毀,返回空指針給S
StackNode *DestroyStack(StackNode*S){StackNode *p = S->next;while(p){free(S);S = p;p = p->next;}printf("銷毀成功\n");return NULL;
}//清空
void ClearStack(StackNode*S){printf("清空\n");StackNode *p = S;while(p!=NULL){p->data = 0;p = p->next;}printf("清空成功\n");
}//判空
int StackEmpty(StackNode*S);//棧長度
int StackLength(StackNode*S){int len = 0;StackNode *p = S;while(p!=NULL){len++;p = p->next;}return len;
}//獲取棧頂元素,不修改指針位置
ElemType GetTop(StackNode*S){if(S!=NULL){printf("棧頂元素為%d", S->data);return S->data;}else{printf("空鏈棧無棧頂元素\n");return NULL;}
}//插入棧頂,返回指針指向當(dāng)前棧頂
StackNode *Push(StackNode*S, ElemType e){StackNode *p = NULL;p = (StackNode *)malloc(sizeof(StackNode));p->data = e;p->next = S;S = p;printf("%d入棧成功\n", e);return S;
}//刪除棧頂,返回指針指向當(dāng)前棧頂
StackNode *Pop(StackNode *S, ElemType *e){StackNode *p = NULL;//用于暫存刪除元素if(S == NULL){printf("空鏈棧,刪除失敗\n");return NULL;}*e = S->data;p = S;S = S->next;free(p);printf("%d出棧成功\n",*e);return S;
}//從棧頂依次遍歷
void StackTraverse(StackNode *S){StackNode *p = S;if(p == NULL){printf("空鏈棧\n");return;}while(p != NULL){printf("%d ", p->data);p = p->next;}printf("\n");
}int main(void){StackNode *S;ElemType e;//初始化測試S = InitStack(S);// //獲取棧頂元素測試
// GetTop(S);
// S = Push(S, 999);
// GetTop(S);//入棧測試S = Push(S, 1);S = Push(S, 3);S = Push(S, 2);S = Push(S, 4);S = Push(S, 7);//棧長測試printf("棧長%d\n",StackLength(S));//遍歷測試
StackTraverse(S);// //出棧測試
// S = Pop(S, &e);
// S = Pop(S, &e);
// S = Pop(S, &e);
// //printf("測試e是否改變: %d\n",e);
// S = Pop(S, &e);
// StackTraverse(S);// //清空測試
// ClearStack(S);
// StackTraverse(S);//// //銷毀測試
// S = DestroyStack(S);
// StackTraverse(S);return 0;
}
?
轉(zhuǎn)載于:https://www.cnblogs.com/powerzzjcode/p/10889112.html
總結(jié)
- 上一篇: Python解答力扣网站题库简单版---
- 下一篇: 【Task5(2天)】模型调参