《数据结构与程序设计》03-Linked Stacks and Queues

  1. 链式结构的基础:(结点和链)
  • .hpp
typedef Stack_entry Node_entry;

struct Node{
	//数据成员
	Node_entry entry;
	Node *next;
	//构造函数
	Node();
	Node(Node_entry item, Node *add_on = NULL);
};
  • .cpp
Node::Node(){   
	next = NULL;
}

Node::Node(Node_entry item, Node *add_on){    
	entry = item;    
	next = add_on;
}
  1. 链栈的实现:
  • .hpp
#include <iostream>
#include <cstdio>
using namespace std;

typedef char Stack_entry;

enum Error_code{    
	overflow, underflow, success
};
 
class Stack{
protected:    
	Node *top_node;
public:    
	Stack();  
	~Stack();  
	bool empty() const;    
	Error_code push(const Stack_entry & item);    
	Error_code pop();    
	Stack_entry top(Stack_entry & item) const; 
	//重载赋值操作符
	void Stack::operator = (const Stack & original);
	//拷贝构造函数
	Stack(const Stack & original);
	void print();
};
  • .cpp
Stack::Stack(){    
	top_node = NULL;
}

Stack::~Stack(){    
	while (! empty())        
		pop();
}

Error_code Stack::push(const Stack_entry & item){    
	Node *new_top = new Node(item, top_node);    
	if(new_top == NULL) return overflow;
    	top_node = new_top;    
    	return success;
}

Error_code Stack::pop(){    
	Node *old_top = top_node;    
	if(top_node == NULL) return underflow;    
	top_node = old_top->next;    
	delete old_top;    
	return success;
}

Stack_entry Stack::top(Stack_entry & item) const{    
	if(top_node == NULL) return 0;    
	item = top_node->entry;    
	return item;
}
	
bool Stack::empty() const{    
	if(top_node == NULL) return true;    
	else return false;
}

void Stack::operator = (const Stack & original){
	Node *new_top,*new_copy,*original_node = original.top_node;
	if(original_node == NULL) new_top = NULL;
	else{
		new_copy = new_top = new Node(original_node->entry);
		while(original_node->next != NULL){
			original_node = original_node->next;
			new_copy->next = new Node(original_node->entry);
			new_node = new_copy->next;
		}
	}
	while (!empty())
		pop();
	top_node = new_top;
}

Stack::Stack(const Stack & original){	
	Node *new_copy,*original_node = original.top_node;
 	if(original_node == NULL) top_node = NULL;
 	else{
  		top_node = new_copy = new Node(original_node->entry);
  		while(original_node->next != NULL){
   			original_node = original_node->next;
   			new_copy->next = new Node(original_node->entry);
   			new_node = new_copy->next;
  		}
 	}
}

void Stack::print(){    
	Node <char>*new_node = top_node;     
	while(new_node != NULL){        
		cout << new_node->entry << "   ";        
		new_node = new_node->next;    
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值