插入操作和删除操作均在链表头部进行,链表尾部就是栈底,栈顶指针就是头指针 不需要预先分配固定大小 动态增长和收缩
typedef int data_t ; /*定义栈中数据元素数据类型*/ typedef struct node_t { data_t data; /*数据域*/ struct node_t * next; /*链接指针域*/ } linkstack_t ; /*链栈类型定义*/ # include <stdio.h> # include <stdlib.h> # include "linkstack.h" linkstackstack_create ( ) { linkstack s; s= ( linkstack) malloc ( sizeof ( listnode) ) ; if ( s== NULL ) { printf ( "malloc failed\n" ) ; return NULL ; } s-> data= 0 ; s-> next= NULL ; return s; } int stack_push ( linkstack s, data_t value) { linkstack p; if ( s== NULL ) { printf ( "s is NULL\n" ) ; return - 1 ; } p= ( linkstack) malloc ( sizeof ( listnode) ) ; if ( p== NULL ) { printf ( "malloc failed\n" ) ; return - 1 ; } p-> data= value; //p->next = NULL; p-> next= s-> next; s-> next= p; return 0 ; } data_t stack_pop ( linkstack s) { linkstack p; data_t t; p= s-> next; s-> next= p-> next; t= p-> data; free ( p) ; p= NULL ; return t; } int stack_empty ( linkstack s) { if ( s== NULL ) { printf ( "s is NULL\n" ) ; return - 1 ; } return ( s-> next== NULL ? 1 : 0 ) ; } data_t stack_top ( linkstack s) { return ( s-> next-> data) ; } linkstackstack_free ( linkstack s) { linkstack p; if ( s== NULL ) { printf ( "s is NULL\n" ) ; return NULL ; } while ( s!= NULL ) { p= s; s= s-> next; printf ( "free:%d\n" , p-> data) ; free ( p) ; } return NULL ; } typedef int data_t ; typedef struct node { data_t data; struct node * next; } listnode, * linkstack; linkstackstack_create ( ) ; int stack_push ( linkstack s, data_t value) ; data_t stack_pop ( linkstack s) ; int stack_empty ( linkstack s) ; data_t stack_top ( linkstack s) ; linkstackstack_free ( linkstack s) ; # include <stdio.h> # include <stdlib.h> # include "linkstack.h" int main ( int argc, const char * argv[ ] ) { linkstack s; s= stack_create ( ) ; if ( s== NULL ) return - 1 ; stack_push ( s, 10 ) ; stack_push ( s, 20 ) ; stack_push ( s, 30 ) ; stack_push ( s, 40 ) ; while ( ! stack_empty ( s) ) { printf ( "pop:%d\n" , stack_pop ( s) ) ; } s= stack_free ( s) ; return 0 ; }