栈的实现方式:顺序栈和链表栈 C语言

用栈解决进制转换的问题,将十进制9000转换为八进制

顺序栈实现方法,是从内存中开辟连续的一块存储空间,用数组方法实现的

#include <stdio.h>
#include <malloc.h>

#define MAX 50

//顺序栈方法,栈的构造********************* 
struct Stack{
	int stack_arr[MAX];
	int top;
	
};
void InitStack(Stack *S)
{
	S->top=-1;
}
void ClearStack(Stack *S)
{
	InitStack(S);
}
bool IsEmpty(Stack *S)
{
	if(S->top==-1) return true;
	else return false; 
}
bool IsFull(Stack *S)
{
	if(S->top == MAX) return true;
	else return false;
}
int Push(Stack *S,int x)
{
	if(IsFull(S) ) return false;
	else
	{
		S->top++;
		S->stack_arr[S->top]=x;
		return true;
	}
}
int Pop(Stack *S,int* x)
{
	if(IsEmpty(S) ) return false;
	else
	{
		*x=S->stack_arr[S->top];
		S->top--;
		return true;
	}
}
int GetTop(Stack *S,int *x)
{
	if(IsEmpty(S) ) return false;
	else
	{
	    *x=S->stack_arr[S->top];
	    return true;	
	}
}
//***************************************
int main()
{	
	void Shift(int m);
	int m=9000;
	Shift(m);
	
	return 0;
} 
void Shift(int m)
{
	int *x=(int *)malloc(sizeof(int));//通过malloc对新定义的指针进行分配地址 
	Stack *Sp=(Stack*)malloc(sizeof(Stack));
	InitStack(Sp);
	while(m!=0)
	{
		Push(Sp,m%8);
	    m=m/8;
	}
   while(IsEmpty(Sp)==false) 
	{	
		Pop(Sp,x);
		printf("%d",*x);		
	}
	free(Sp);
	free(x); 
	
}
链表实现

#include <stdio.h>
#include <malloc.h>
#define MAX 50
 //链表实现栈 
typedef int ElementType;//目的为了比较容易的改变,以适应其他类型 
struct Node
{
	ElementType data;
	Node *next;
};

typedef Node* LinkList;//头指针其实与next同类型,改为LinkList称呼是为了提高可读性 
void InitStack(LinkList S)
{
	S->next=NULL;//S是在形参中定义好的,无需再次分配内存 
}
void ClearStack(LinkList S)
{
	S->next=NULL;
}
int IsEmpty(LinkList S)
{
	if(S->next=NULL) return true;
	else return false;
}
int Push(LinkList S,ElementType x)
{
	Node* temp=(Node*)malloc(sizeof(Node) );
	temp->data=x;
	temp->next=S->next;
	S->next=temp;
	 
}
int Pop(LinkList S,ElementType* x)
{
	if(S->next==NULL) return false;
	else
	{
		*x=S->next->data;
		S->next=S->next->next;
		
		return true;
	}
}
int GetTop(LinkList S,ElementType* x)
{
	if(S->next==NULL) return false;
	else
	{
		*x=S->next->data;
		return true;
	}
}
int main()
{
	void shift(int m);
	int m=9000;
	shift(m);
	
	return 0;
}
void shift(int m)
{
	LinkList Sp=(LinkList)malloc(sizeof(Node));
	InitStack(Sp);
	while(m!=0)
	{
		Push(Sp,m%8);
		m=m/8;
	}
	while(Sp->next!=NULL)
	{
		//printf("ddd");
		int* ptr=(int*)malloc(sizeof(int) );
		Pop(Sp,ptr);
		printf("%d",*ptr);
	}
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值