#include
#include
#include
//动态栈,由链表实现 ,上面节点指向下面一个节点
//结构体:节点(表示一个元素)
typedef struct Node
{
int data;
struct Node * pNext;
}NODE,*PNODE;
//结构体:栈,栈顶节点的指针,栈底节点指针(栈底指针指向栈底节点的下一个存储空间,因为是初始化的时候分配的空间,此时还没有插入节点)。
typedef struct Stack
{
PNODE pTop;
PNODE pButtom;
} STACK,*PSTACK;
//为栈分配内存
void init(PSTACK pStack);
//压栈
void push(PSTACK pStack,int val);
//遍历
void traverse(PSTACK pStack);
//弹栈,把出栈的节点的数据存入给定的变量中(给地址)
bool pop(PSTACK pStack,int * val);
int main(void)
{
//初始化
STACK stack;
init(&stack);
//压栈
push(&stack,1);
push(&stack,2);
push(&stack,3);
push(&stack,4);
//遍历
traverse(&stack);
//弹栈
int a = 0;
pop(&stack,&a);
printf("\n出栈的元素是:%d\n",a);
//遍历
traverse(&stack);
getchar();
return 0;
}
//初始化栈
void init(PSTACK pStack)
{
//为节点分配内存
pStack->pTop = (PNODE)malloc(sizeof(NODE));
if(pStack->pTop == NULL)
{
printf("动态内存分配失败!\n");
exit(-1);
}else
{
//栈顶指针和栈底指针相等 ,都指向初始节点
pStack->pButtom = pStack->pTop;
pStack->pTop->pNext = NULL; //初始节点的下个节点为NULL
}
}
//压栈
void push(PSTACK pStack,int val)
{
//创建一个节点
PNODE pNewNode= (PNODE)malloc(sizeof(NODE));
pNewNode->data = val;//数据域赋值
pNewNode->pNext = NULL;//指针域为空(栈顶)
pNewNode->pNext = pStack->pTop;//新加入的节点的下一个节点指向原来的栈顶节点
pStack->pTop = pNewNode;//栈顶指针指向新压入的节点
return;
}
//遍历
void traverse(PSTACK pStack)
{
PNODE pNode = pStack->pTop;
while(pNode != pStack->pButtom)
{
printf("%d\t",pNode->data);
pNode = pNode->pNext;
}
}
//弹栈
bool pop(PSTACK pStack,int * val)
{
if(pStack->pTop == pStack->pButtom)
{
return false;
}
*val = pStack->pTop->data;
PNODE r= pStack->pTop;//记录栈顶节点
pStack->pTop = pStack->pTop->pNext;
free(r);
r=NULL;//释放原来栈顶节点的空间
return true;
}
本文题目:c模拟链表操作,笔记
本文地址:
http://bzwzjz.com/article/ppgeoe.html