码迷,mamicode.com
首页 > 其他好文 > 详细

2.1.2链栈的设计与实现(推荐)

时间:2015-05-22 15:14:29      阅读:133      评论:0      收藏:0      [点我收藏+]

标签:   链表   

链表栈的基本操作包括栈的建立、求长度、取栈顶元素、入栈、出栈、判断栈是否空等具体操作。

//调试环境:DevC++

//库文件和预设定义
#include <stdio.h>
#include <stdlib.h>

#define Stack_Length 6
#define OK 1
#define ERROR 0

typedef int SElemType;
//存储形式
typedef struct SNode
{
	SElemType data;
	struct SNode *next;
}SNode, *LinkStack;

/****-------------------------------------------------------------****/
//函数名:CreateTwo(LNode *head,int n) 
//参数:  (传入)LNode *head 传入一个链指针
//       (传入)int n,传入线性表节点数量
//作用:  建立一个空栈
//返回值:  无
/****-------------------------------------------------------------****/

void CreateTwo(LinkStack &head, int n)
{
	int i;
	SNode *p; //定义新结点指针
	
	
	//建立带头结点的线性链表
	head = (LinkStack)malloc(sizeof(SNode));
	head->next = NULL;
	
	printf("Please input the data for LinkList Nodes: \n");
	for(i = n; i > 0; i--) {
		p = (SNode*)malloc(sizeof(SNode));//为新结点申请空间,即创建一个新结点
		scanf("%d", &p->data); //新结点赋值
		//新结点插入到表头
		p->next = head->next;
		head->next = p;
	}
}

/****--------------------------------------------------------------****/
//函数名:Push(LinkStack &top, SElemType e)
//参数: (传入)LinkStack &top,栈顶指针
//      (传入)SElemType e入栈元素
//作用:入栈
//返回值:int 型,返回1表示入栈成功,0表示失败
/****-------------------------------------------------------------****/

int Push(LinkStack &top, SElemType e)
{
	SNode *q;
	q = (LinkStack)malloc(sizeof(SNode));//创建入栈元素结点
	
	//创建结点失败处理
	if(!q)
	{
		printf("Overflow!\n");
		return(ERROR);
	}
	q->data = e;
	q->next = top->next;//入栈元素结点插入栈顶 
	top->next = q;
	
	return (OK);
}

/****----------------------------------------------------------****/
//函数名:Pop(LinkStack &top, SElemType &e)
//参数: (传入)LinkStack &top, 栈顶指针
//      (传出)SElemType e 出栈元素
//作用:出栈
//返回值:int 型,返回1表示出栈成功,0表示失败
/****-----------------------------------------------------------****/
int Pop(LinkStack &top, SElemType &e)
{
	SNode*q;  //定义临时存储栈顶结点的指针
	if(!top->next)
	{
		printf("error");
		return (ERROR);
	}
	e = top->next->data;
	q = top->next;
	top->next = q->next; //删除栈顶元素
	free(q);
	return(OK);
}

/****---------------------------测试程序---------------------------*****/

int main()
{
	int e;
	//建立一个栈
	LinkStack top;
	//使用建立方法二
	CreateTwo(top, 3);
	
	//显示栈元素
	LinkStack p;
	printf("\nThe old LinkStack is(top to bottom) : \n");
	p = top;
	while(p->next)
	{
		p = p->next;
	    printf("%d ",p->data);
	}
	printf("\nPlease input the data to push : ");
	scanf("%d", &e);
	
	//入栈操作
	if(Push(top, e))
	printf("success to push");
		
	//显示栈元素,验证入栈操作是否成功
	printf("\nThe new LinkStack is : \n");
	while(top->next)
	{
		top = top->next;
		printf("%d ",top->data);
	}
	return 0;
}
	 


2.1.2链栈的设计与实现(推荐)

标签:   链表   

原文地址:http://blog.csdn.net/bao_libra/article/details/45916857

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!