双向链表/单链表实现栈

这篇博客介绍了如何使用C++实现双向链表和单链表的栈结构。作者详细地展示了栈的构造、析构、压栈、弹栈、获取栈顶和栈底元素的方法。在双向链表的实现中,采用了头节点和尾节点,而单链表则使用了头插法。同时,博客强调了在操作中需要注意的空栈判断。
摘要由CSDN通过智能技术生成

双向链表

struct node {
	int val;
	node* next;
	node* pre;
};

class stack {
public:
	stack() {
		head=new node;//带头节点
		head->next = nullptr;//建立的时候要指向空
		tail = head;
	}
	~stack() {
		while (tail) {
			p = tail;
			tail = tail->next;
			delete p;
		}
		delete head;
	}

	void push(int x) {
		
		p = new node;
		p->val = x;
		tail->next = p;
		p->pre = tail;
		tail = p;
	}

	void pop() {
		if (isEmpty()) {//注意判空!!
			cout << "栈为空!" << endl;
			return;
		}
		p = tail;
		tail = tail->pre;
		p->pre = nullptr;
		tail->next = nullptr;
		delete p;
	}

	int top() {
		if (isEmpty()) {
			cout << "栈为空!" << endl;
			return -1;
		}
		return tail->val;
	}

	int bottom() {
		if (!isEmpty()) {
			cout << "栈为空!" << endl;
			return -1;
		}
		return head->next->val;
	}

	bool isEmpty() {
		if (tail == head)
			return 1;
		return 0;
	}

	bool ifFull() {
		if (isEmpty())
			return 0;
		return 1;
	}
private:
	node* tail,*head,*p;
};

单链表

struct node {
	int val;
	node* next;
};

class stack {
public:
	stack() {
		head=new node;
		head->next = nullptr;
		tail = head;
	}


	void push(int x) {
		
		p = new node;
		p->val = x;
		p->next=head->next;//头插法
		head->next=p;
		tail = p;
	}

	void pop() {
		if (isEmpty()) {//判空
			cout << "栈为空!" << endl;
			return;
		}
		p = tail;
		head->next = p->next;
		p->next = nullptr;
		delete p;
		tail = head->next;
	}

	int top() {
		if (isEmpty()) {
			cout << "栈为空!" << endl;
			return -1;
		}
		return tail->val;
	}
	//如果要实现,只能多加一个指针一直指向栈尾
	//int bottom() {
	//	if (!isEmpty()) {
	//		cout << "栈为空!" << endl;
	//		return -1;
	//	}
	//	return head->next->val;
	//}

	bool isEmpty() {
		if (!tail||tail == head)//当pop到为0||一开始就没有插入
			return 1;
		return 0;
	}

	bool ifFull() {
		if (isEmpty())
			return 0;
		return 1;
	}
private:
	node* tail,*head,*p;
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值