鏈表棧實現

鏈表棧實現,代碼如下:

// test.cpp : 定義控制檯應用程序的入口點。
//

#include "stdafx.h"
#include <iostream>
using namespace std;

typedef struct STNode
{
	int data;
	int size;
	STNode* next;
}stNode;

void InitStack(stNode* top);
int IsEmpty(stNode* top);
int PushStack(stNode* top, int elem);
int PopStack(stNode* top, int* elem);

int _tmain(int argc, _TCHAR* argv[])
{
	int elem = 0;
	stNode* stpTop = (stNode*)malloc(sizeof(stNode));
	InitStack(stpTop);
	PushStack(stpTop, 1);
	PushStack(stpTop, 2);

	while(stpTop->size > 0)
	{
		PopStack(stpTop, &elem);
		cout<<"elem="<<elem<<endl;
	}

	system("pause");
	return 0;
}

void InitStack(stNode* top)
{
	top->data = 0;
	top->size = 0;
	top->next = NULL;
}

int IsEmpty(stNode* top)
{
	if(NULL == top->next && top->size == 0)
		return 1;
	return 0;
}

int PushStack(stNode* top, int elem)
{
	stNode* stpNode = (stNode*)malloc(sizeof(stNode));
	if(NULL == stpNode)
		return 0;
	top->size ++;
	stpNode->data = elem;
	stpNode->next = top->next;
	top->next = stpNode;
	return 1;
}

int PopStack(stNode* top, int* elem)
{
	if(IsEmpty(top))
		return 0;
	stNode* stpNode = (stNode*)malloc(sizeof(stNode));
	if(NULL == stpNode)
		return 0;
	top->size --;
	stpNode = top->next;
	*elem = stpNode->data;
	top->next = stpNode->next;
	free(stpNode);
	return 1;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章