C语言实现栈(链式栈)
由于栈的插入、删除操作只能在一端进行,而对于线性链表来说,在首端插入或=删除比在尾端要容易一些,所以,将线性链表的首端作为栈顶端,即将头指针作为栈顶指针。
1、结构体
1 typedef struct node{ 2 typename pos; 3 struct node *next; 4 }Node; 5 6 typedef struct my_stack{ 7 Node *top; 8 }Stack;
2、初始化
1 Stack *create_stack(){ 2 Stack *s; 3 s = (Stack*)malloc(sizeof(Stack)); 4 if(s != NULL) s->top = NULL; 5 else printf("error1\n"); 6 return s; 7 }
3、判断栈是否为空
1 int isempty(Stack *s) { 2 return s->top == NULL; 3 }
4、入栈
1 void push_stack(Stack *s, position value) { 2 Node *New; 3 New = (Node *)malloc(sizeof(Node)); 4 if(New != NULL) { 5 New->pos = value; 6 New->next = s->top; 7 s->top = New; 8 } else printf("error2\n"); 9 }
5、出栈
1 void pop_stack(Stack *s) { 2 Node *p; 3 p = s->top; 4 s->top = s->top->next; 5 free(p); 6 }
6、获取栈顶元素
1 typename get_top(Stack *s) { 2 return s->top->pos; 3 }