其他分享
首页 > 其他分享> > 07、进制转换-链式栈LinkStack

07、进制转换-链式栈LinkStack

作者:互联网

LinkStack.h

#pragma once
typedef int DataType;
typedef struct node{
	DataType data;
	struct node* next;
}LStackNode,*LinkStack;

void InitStack(LinkStack* top);
int StackEmpty(LinkStack top);
int PushStack(LinkStack top, DataType e);
int PopStack(LinkStack top, DataType* e);
int GetTop(LinkStack top, DataType* e);
int StackLength(LinkStack top);
void DestoryStack(LinkStack top);
void PrintStack(LinkStack top);
void Coversion(int N);

LinkStack.cpp

#include<cstdio>
#include"LinkStack.h"


void InitStack(LinkStack* top)
{
	*top = new LStackNode;
	(*top)->next = nullptr; /*将链表的头结点的指针域置为空*/
}

int StackEmpty(LinkStack top)
{
	if (top->next == nullptr) {
		return 1;
	}
	else {
		return 0;
	}
}
/*使用链表的头插法*/
int PushStack(LinkStack top, DataType e)
{
	LStackNode* p;
	p = new LStackNode;
	p->data = e;
	p->next = top->next;
	top->next = p;
	return 1;
}

int PopStack(LinkStack top, DataType* e)
{

	LStackNode* p;
	p = top->next;
	if (p == nullptr) {
		printf("栈已空\n");
		return 0;
	}
	else {
		*e = p->data;
		delete p;
		return 1;
	}

}

int GetTop(LinkStack top, DataType* e)
{
	LStackNode* p;
	p = top->next;
	if (p == nullptr) {
		printf("栈已空\n");
		return 0;

	}
	else {
		*e = p->data;
		return 1;
	}
}

int StackLength(LinkStack top)
{
	LStackNode* p;
	int count = 0;
	p = top;
	while (p->next != nullptr)
	{
		p = p->next;
		count++;
	}
	return count;
}

void DestoryStack(LinkStack top)
{
	LStackNode* p, * q;
	p = top;
	while (p!=nullptr) {
		q = p;
		p = p->next;
		delete q;
	}
}

void PrintStack(LinkStack top)
{
	LStackNode* p;
	p = top;
	while (p->next != nullptr)
	{
		p = p->next;
		printf("%d", p->data);
	}
	printf("\n");
}

void Coversion(int N)
{
	LinkStack top;
	InitStack(&top);
	do {
		PushStack(top, N % 8);
		N = N / 8;
	} while (N != 0);

	PrintStack(top);
	
}

进制转换,辗转相除法,入栈后,将栈打印即可

void test_Conversion() {
	int N;
	printf("输入十进制转化为八进制数:");
	scanf_s("%d", &N);
	Coversion(N);

}

标签:LinkStack,LStackNode,07,int,top,next,链式,void
来源: https://blog.csdn.net/weixin_33232568/article/details/122041470