- 《算法導論》10.2-2 用一個單鏈表實現一個棧,要求操做push和pop的運行時間仍爲O(1)
#include <singlelinkedlist.h>
template<typename Object>
class StackByList
{
public:
void push(const Object& object)
{
sll.push_front(object);
}
void push(Object&& object)
{
sll.push_front(std::move(object));
}
Object& top()
{
return sll.front();
}
const Object& top() const
{
return sll.front();
}
void pop()
{
sll.pop_front();
}
private:
SingleLinkedList<Object> sll;
};
void testStackByList()
{
using namespace std;
struct Student
{
const char* name;
int age;
bool operator ==(const Student& rhs) const
{
return 0 == strcmp(name, rhs.name) && age == rhs.age;
}
};
constexpr int NUM = 5;
Student students[NUM] = {Student{"Tom", 12},Student{"Micheal", 13},
Student{"Anna", 14},Student{"Lily", 10},
Student{"James", 19}};
StackByList<Student> sbl;
for(int i = 0; i != NUM; ++i)
sbl.push(students[i]);
decltype(sbl) cp(sbl);
decltype(cp) mv(std::move(cp));
mv = std::move(sbl);
for(int i = 0; i != NUM; ++i)
{
Student& stu = mv.top();
cout << "name: " << stu.name << " age: " << stu.age << endl;
mv.pop();
}
}
/*test output:
name: James age: 19
name: Lily age: 10
name: Anna age: 14
name: Micheal age: 13
name: Tom age: 12
*/
隨筆《帶哨兵的單向循環鏈表》給出了singlelinkedlist.h的內容html