操作受限的链表
如果进行头插,就只能头删
如果进行尾插,就只能进行尾删
- #ifndef __LINK_STACK_H__
- #define __LINK_STACK_H__
- #include
- #include
- typedef struct link_stack{
- int data;
- struct link_stack *next;
- }link_stack,*link_p;
-
- //桟顶指针的类型
- //桟顶指针应该独立于桟存在,为了和桟中元素不同
- typedef struct top_t{
- int len;//记录链桟的长度
- link_p ptop;//桟顶指针
- }top_t,*top_p;
-
- //申请桟顶指针
- top_p creat_top();
- //申请节点的函数
- link_p creat_node(int data);
- //判空
- int empty(top_p T);
- //入桟
- void push_stack(top_p T,int data);
- //出桟
- void pop_stack(top_p T);
- //遍历
- void show_stack(top_p T);
- //销毁链桟
- void free_stack(top_p T);
-
- #endif
- //申请桟顶指针
- top_p creat_top(){
- top_p top=(top_p)malloc(sizeof(top_t));
- if(top==NULL){
- printf("空间申请失败\n");
- return NULL;
- }
- top->len=0;
- top->ptop=NULL;//刚申请桟指针没有指向元素
- return top;
- }
- //申请节点的函数
- link_p creat_node(int data){
- link_p new=(link_p)malloc(sizeof(link_stack));
- if(new==NULL){
- printf("申请空间失败\n");
- return NULL;
- }
- new->data=data;
- return new;
- }
- //判空
- int empty(top_p T){
- if(T==NULL){
- printf("申请空间失败\n");
- return 0;
- }
- return T->ptop==NULL?1:0;
-
- }
- //入桟
- void push_stack(top_p T,int data){
- if(T==NULL){
- printf("入参为空\n");
- return;
- }
- link_p new=creat_node(data);
- new->next=T->ptop;
- T->ptop=new;
- T->len++;
- }
- void pop_stack(top_p T){
- if(T==NULL){
- printf("入参为空\n");
- return;
- }
- if(empty(T)){
- printf("链桟为空,无需出桟\n");
- return;
- }
- link_p p=T->ptop;
- while(p->next->next!=NULL){
- p=p->next;
- }
- link_p del=p->next;
- p->next=del->next;
- free(del);
- T->len--;
- }
- //遍历
- void show_stack(top_p T){
- if(T==NULL){
- printf("入参为空\n");
- return;
- }
- if(empty(T)){
- printf("链桟为空\n");
- return;
- }
- link_p p=T->ptop;
- while(p!=NULL){
- printf("%d ",p->data);
- p=p->next;
- }
- putchar(10);
- }
- //销毁链桟
- void free_stack(top_p T){
- if(T==NULL){
- printf("入参为空\n");
- return;
- }
- if(empty(T)){
- printf("链桟为空\n");
- return;
- }
- //循环出桟
- link_p p=T->ptop->next;
- link_p del;
- while(p!=NULL){
- del=p;
- p=p->next;
- free(del);
- del=NULL;
- }
-
- }