19.4.5用栈实现抽象数据类型
这里简直太牛了,直接定义一个结构体类型的栈,里面是一个头节点(也是一个指针),后面直接定义一个栈的指针对象,那么就可以随意改变栈里面的内容(也就是头节点),就能达到链表操作的所有要求。
切身体会:如果要定义一个链表,那么直接先定义一个节点类型,然后再定义一个链表类型(里面就 放置这个链表的头节点就可以了,以后只要定义一个这样的链表类型(最好是动态分配定义,
后面直接可以用指针操作这个链表了),不管后面如何操作,执行任何操作,都太方便了。
//stackADT_linkList.c
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h> //c99 only
#include "stackADT_linkList.h"
struct node{
struct node * next;
Item data;
};
struct stack_type{
struct node * top;
};
void terminate(const char * message)
{
printf("%s\n",message);
exit(EXIT_FAILURE);
}
Stack create(void)
{
Stack first_node = malloc(sizeof(struct stack_type));
if(first_node == NULL)
terminate("Error in create:no space to create new node.\n");
first_node -> top = NULL;
return first_node;
}
bool is_full(const Stack s)
{
return true;
}
bool is_empty(const Stack s)
{
return s->top == NULL;
}
void destroy(Stack s)
{
while(s->top != NULL)
{
pop(s);
}
free(s);
}
void push(Stack s,Item t)
{
struct node * new_node = malloc(sizeof(struct node));
if(new_node == NULL)
{
terminate("Error in push,can't creat new node.\n");
}
new_node -> data = t;
new_node -> next = s -> top;
s -> top = new_node;
}
Item pop(Stack s)
{
if(s -> top == NULL)
{
terminate("Error in pop:stack is empty.\n");
}
struct node * old_node = s -> top;
s -> top = s -> top -> next;
Item data = old_node -> data;
free(old_node);
}
void print(const Stack s)
{
struct node * ptr = s -> top;
if(ptr == NULL)
printf("Stack is empty.\n");
while(ptr != NULL)
{
printf("%d ",ptr -> data);
ptr = ptr -> next;
}
printf("\n");
}
//main.c
#include "stackADT_linkList.h"
int main(void)
{
Stack s1,s2;
s1 = create();
s2 = create();
push(s1,1);
print(s1);
push(s1,2);
print(s1);
pop(s1);
print(s1);
pop(s1);
print(s1);
destroy(s1);
destroy(s2);
return 0;
}
//文件 stackADT_linkList.h
#ifndef STACK_ADT_LINKLIST
#define STACK_ADT_LINKLIST
#include <stdbool.h> //c99 only
typedef int Item;
struct stack_type; //declare a incomplete type
typedef struct stack_type *Stack;
Stack create(void);
void terminate(const char *);
bool is_full(const Stack );
bool is_empty(const Stack );
void destroy(Stack );
void push(Stack ,Item );
Item pop(Stack );
void print(const Stack );
#endif
运行结果:
1
2 1
1
Stack is empty.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)