《C语言》链式正向栈

《C语言》链式正向栈

Main.c

#include "Stack.h"



void main()
{

	/*****************先进后出(逆序)*****************/
#if 0
	Stack* P_Stack = NULL;

	for (int i = 0; i < 10; i ++ )
	{
		Push(&P_Stack, i * 10, i);


	}
	while (NULL != P_Stack)
	{
		Stack temp;
		Pop(&P_Stack, &temp);
		printf("%d\n", temp.Data);
	}

#endif

	/*****************进一个出一个(顺序)*****************/
#if 0
	Stack* P_Stack = NULL;

	for (int i = 0; i < 10; i++)
	{
		Push(&P_Stack, i * 10, i);

		while (NULL != P_Stack)
		{
			Stack temp;
			Pop(&P_Stack, &temp);
			printf("%d\n", temp.Data);
		}
	}
#endif


	/*****************十进制转二进制*****************/
#if 0
	Stack* P_Stack = NULL;

	int Num = 10;
	while (Num)
	{
		Push(&P_Stack,Num%2,0);
		Num /= 2;
	}

	while (NULL != P_Stack)
	{
		Stack temp;
		Pop(&P_Stack, &temp);
		printf("%d\n", temp.Data);
    }
#endif

	system("pause");
}

Stack.h

#pragma once


#ifdef __cplusplus
extern "C"
{
#endif

#include <stdio.h>
#include <stdlib.h>

	typedef int DataType;

	typedef struct Stack
	{
		DataType Data;
		int ID;
		struct Stack* P_Next;
	}Stack;

	//初始化节点
	void InitNode(Stack* P_Node);
	//压栈
	void Push(Stack** PP_Head, DataType Data, int ID);
	//出栈
	void Pop(Stack** PP_Head,Stack* PopNode);
	//显示栈
	void Show(Stack* P_Head);
	//销毁栈
	void Destroy(Stack** PP_Head);

#ifdef __cplusplus
}
#endif

Stack.h

#include "Stack.h"



//初始化
void InitNode(Stack* P_Node)
{
	if (NULL != P_Node)
	{
		P_Node->P_Next = NULL;
	}

}

//压栈
void Push(Stack** PP_Head, DataType Data, int ID)
{
	Stack* P_New = (Stack*)malloc(sizeof(Stack));
	P_New->P_Next = NULL;
	P_New->Data = Data;
	P_New->ID = ID;

	if (NULL == *PP_Head)
	{
		*PP_Head = P_New;
	}
	else
	{
		Stack* P_Bak = *PP_Head;
		while (NULL != P_Bak->P_Next)
		{
			P_Bak = P_Bak->P_Next;
		}
		P_Bak->P_Next = P_New;
	}
}

//出栈
void Pop(Stack** PP_Head, Stack* PopNode)
{
	if (NULL == *PP_Head)
	{
		return;
	}
	else if (NULL == (*PP_Head)->P_Next)
	{
		PopNode->ID = (*PP_Head)->ID;
		PopNode->Data = (*PP_Head)->Data;

		free(*PP_Head);
		*PP_Head = NULL;
	}
	else
	{
		Stack* P_Bak = *PP_Head;
		while (NULL != P_Bak->P_Next->P_Next)
		{
			P_Bak = P_Bak->P_Next;
		}
		PopNode->ID = P_Bak->P_Next->ID;
		PopNode->Data = P_Bak->P_Next->Data;
		free(P_Bak->P_Next);
		P_Bak->P_Next = NULL;
	}
}

//显示栈
void Show(Stack* P_Head)
{
	if (NULL == P_Head)
	{
		return;
	}
	else
	{
		printf("%p\t%p\t%d\t%d\n", P_Head, P_Head->P_Next, P_Head->Data, P_Head->Data);
		Show(P_Head->P_Next);
	}
}

//销毁栈
void Destroy(Stack** PP_Head)
{
	if (NULL != *PP_Head)
	{
		Stack* P1 = *PP_Head;
		Stack* P2 = NULL;
		while (NULL != P2)
		{
			P2 = P1->P_Next;
			P1 = P2->P_Next;
			free(P2);
			P2 = NULL;
		}
		free(*PP_Head);
		*PP_Head = NULL;
	}
}

猜你喜欢

转载自blog.csdn.net/baidu_41905806/article/details/84889360