#include <iostream>
using namespace std;
#include <string>
typedef string T;
class List{
struct Node{
T data;
Node* next;
Node(const T& t=T()):data(t)
{
next = NULL;
}
};
Node* head;
public:
List():head(NULL)
{
}
void clear()
{
while(head != NULL)
{
Node* q = head->next;
delete head;
head = q;
}
}
~List()
{
clear();
}
void insert_front(const T& t)
{
Node* p = new Node(t);
p->next= head;
head = p;
}
void insert_back(const T& t)
{
Node* p = new Node(t);
if (head==NULL)
head = p;
else
{
get_pointer(size()-1)->next = p;
}
}
void travel()
{
Node* p=head;
while(p != NULL)
{
cout << p->data << ' ';
p = p->next;
}
cout << endl;
}
int size()
{
int cnt = 0;
Node* p = head;
while(p != NULL)
{
cnt++;
p = p->next;
}
return cnt;
}
T get_head()
{
if (head == NULL)
{
throw "no head";
}
return head->data;
}
T get_tail()
{
if (head == NULL)
throw "no tail";
Node* p = head;
while(p->next != NULL)
{
p = p->next;
}
return p->data;
}
bool empty()
{
return head == NULL;
}
int find(const T& t)
{
int pos = 0;
Node* p = head;
while(p != NULL)
{
if (p->data== t)
return pos;
p = p->next;
pos++;
}
return -1;
}
bool update(const T& o, const T& n)
{
int pos = find(o);
if (pos == -1)
return false;
Node* p = get_pointer(pos);
p->data = n;
return true;
}
private:
Node* get_pointer(int pos)
{
Node* p = head;
for (int i=0; i<pos; i++)
p = p->next;
return p;
}
public:
bool erase(const T& t)
{
int pos = find(t);
if (pos == -1)
return false;
if (pos ==0)
{
Node* q = head->next;
delete head;
head = q;
}
else
{
Node* pre = get_pointer(pos-1);
Node *cur = pre->next;
pre->next= cur->next;
delete cur;
}
}
};
class Stack{
List l;
public:
void push(const T& t) //数据入栈
{
l.insert_front(t);
}
void pop() //删除栈顶数据
{
l.erase(l.get_head());
}
T top() //取栈顶上的数据
{
return l.get_head();
}
bool empty() //判断栈是否为空
{
return l.empty();
}
int size() //取得栈中元素个数
{
return l.size();
}
void clear() //清空整个栈
{
l.clear();
}
};
int main()
{
Stack s;
s.push("good");
s.push("morning");
s.push("my");
s.push("dear");
s.push("friend");
while(!s.empty())
{
cout << s.top() << ' ';
s.pop();
}
return 0;
}
栈
最新推荐文章于 2024-09-26 11:41:18 发布