Linux下的C语言编程——用链表实现栈操作

来源:互联网 发布:mac 照片 文件夹 编辑:程序博客网 时间:2024/06/05 03:06

用链表实现栈操作

#include <stdio.h>#include <stdlib.h>struct stack{int num;struct stack *next;};typedef struct stack STACK;typedef struct stack *Link;void creat_stack(Link *head){*head = (Link)malloc(sizeof(STACK));if(!(*head)){printf("malloc error!\n");exit(-1);}(*head)->next = NULL;}void creat_node(Link *newnode){*newnode = (Link)malloc(sizeof(STACK));if(!(*newnode)){printf("malloc error!\n");exit(-1);}}void insert_head(Link *head,Link newnode){newnode->next = (*head)->next;(*head)->next = newnode;}void get_stack(Link head){Link temp = head->next;if(!temp){printf("empty!\n");}while(temp != NULL){printf("num = %d\n",temp->num);temp = temp->next;}}void pop_stack(Link *head){Link temp = (*head)->next;if(!temp){printf("empty!\n");}while(temp != NULL){(*head)->next = temp->next;printf("pop num = %d\n",temp->num);free(temp);temp = (*head)->next;}}int main(){Link head;Link newnode;int i;creat_stack(&head);for(i = 0; i < 10; i++){creat_node(&newnode);newnode->num = i + 1;insert_head(&head,newnode);}get_stack(head);pop_stack(&head);get_stack(head);    return 0;}

0 0
原创粉丝点击