`
Dev|il
  • 浏览: 121811 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
最新评论

链栈的实现

 
阅读更多
#include <iostream>
using namespace std;

#define ElemType int
typedef struct LNode{
	ElemType data;
	struct LNode *next;
}Node;

//链栈
class ListStack{
private:
	Node *head;
	int list_stack_size;
	Node * curr;
public:
	ListStack()
	{
		list_stack_size = 0;
		head = curr = NULL;
	}
	bool push(ElemType e); //入栈
	void pop();
	bool isEmpty();
	ElemType Top();
};

bool ListStack::push(ElemType e)
{
	Node *current = (Node *)malloc(sizeof(Node));
	if(!current)
	{
		cout<<"入栈失败\n";
		return false;
	}
	current->data = e;
	current->next = NULL;
	if(!head)
	{
		head = current;
		curr = current;
	}else
	{
		curr->next = current;
		curr = current;
	}
	this->list_stack_size++;
	return true;
}

void ListStack::pop()
{
	Node *prev, *current = head;
	if(!head->next)
	{
		head = NULL;
		return;
	}
	while(current)
	{
		if(current->next)
		{
			prev = current;
			current = current->next;
		}
		else
			break;
	}
	this->curr = prev;
	this->list_stack_size--;
	prev->next = NULL;
}

bool ListStack::isEmpty()
{
	return head == NULL;
}

ElemType ListStack::Top()
{
	Node *current = head;
	while(current->next)
	{
		current = current->next;
	}
	return current->data;
}
int main()
{
	ListStack stack;
	int e;
	cin>>e;
	while(e)
	{
		stack.push(e % 2);
		e /= 2;
	}
	while(!stack.isEmpty())
	{
		cout<<stack.Top();
		stack.pop();
	}
	cout<<endl;
	return 0;
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics