stack源码解析

1、stack源码解释与测试

调试环境采用的是VS2015,大家可以选择自己合适的编译环境去调试。
stack.h

#ifndef MY_LINKLIST_H
#define MY_LINKLIST_H
#include<vector>
#include<iostream>
using namespace std;
template <typename T> class LinkList
{
	/*
	define the listnode
	*/
	template<typename T> struct ListNode
	{
		T val;
		ListNode<T> *next;
		ListNode<T>(int x) : val(x) {}
	};
private:
	ListNode<T>* head;  //一个伪结点,便于操作
public:
	LinkList<T>() {      //creat a null list
		head = new ListNode<T>(0); head->next = nullptr;
	}
	//~LinkList<T>();
	//creat list by a array
	void creatList(vector<T>& arr);
	//insert x at position i;
	void insElem(int i, T x);
	//get list length
	int getLen();
	//delete a  node at pisition i
	T delElem(int i);
	//check empty
	bool empty() { return !head->next; }
	void printList() {
		ListNode<T>* tmp = head->next;
		while (tmp) {
			cout << tmp->val << " ";
			tmp = tmp->next;
		}
		cout << endl;
		delete tmp;
	}
};
template<typename T>                   //头插法建立链表
void LinkList<T>::creatList(vector<T>& arr) {
	ListNode<T>* s;
	head = new ListNode<T>(0);
	head->next = nullptr;
	for (int i = arr.size() - 1; i >= 0; i--) {
		s = new ListNode<T>(arr[i]);
		s->next = head->next;
		head->next = s;
	}
}
template<typename T>
int LinkList<T>::getLen() {
	int len = 0;
	ListNode<T>* p; p = head->next;
	while (p) {
		len++;
		p = p->next;
	}
	return len;
}
template<typename T>
void LinkList<T>::insElem(int i, T x) {    //example :  1 2 3 4 5 
	if (i <0 || i > getLen())               //i=<0,5> 即插入后i所在的位置
		throw "wrong positon";
	ListNode<T>* p = head;
	for (int j = 0; j < i; j++) {
		p = p->next;
	}
	ListNode<T>* tmp = new ListNode<T>(x);
	tmp->next = p->next;
	p->next = tmp;
}
template<typename T>
T LinkList<T>::delElem(int i) {
	if (i < 0 || i >= getLen())
		throw "wrong position";
	ListNode<T>* p = head;
	for (int j = 0; j < i; j++) {
		p = p->next;
	}
	ListNode<T>* q = p->next;
	p->next = q->next;
	delete q;
}
#endif

Stack_Demo.cpp

#pragma once
#include "Stack.h"
#include<iostream>
#include<vector>
using namespace std;
//测试一个一个序列是否是出栈序列
bool IsPopOrder(vector<int> pushV, vector<int> popV) {
	Stack<int> st;
	int len = pushV.size();
	int i = 0, j = 0;
	while (i < len&&j < len) {
		if (pushV[i] == popV[j]) {
			i++; j++;
		}
		else if (st.Size() > 0 && st.GetTop() == popV[j]) {
			st.Pop();
			j++;
		}
		else {
			st.Push(pushV[i]);
			i++;
		}
	}
	while (j < len) {
		if (st.GetTop() != popV[j]) return false;
		j++;
		st.Pop();
	}
	return true;
}
int main()
{
	vector<int> push = { 1,2,3,4,5 };
	vector<int> pop = { 1,2,3,5,4};
	cout << boolalpha << IsPopOrder(push, pop) << endl;
	system("pause");
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值