一个单向链表,并实现栈和队列
2008-07-15 11:23
1016 查看
以下是本人学习中写的一个简单的链表和棧以及队列的实现,由于时间问题没有注释,但命名都很直观.很多不足之处正在慢慢探索学习中。 代码贴上来显示就有问题,不知道是CSDN的问题还是格式的问题,在我自己机子上没问题的,郁闷! #include using namespace std; #include typedef double 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); Node* q=head; if(head==NULL) head=p; else{ while(q->next!=NULL) q=q->next; q->next=p; } } void travel() { Node* p=head; while(p!=NULL) { cout<data<<' '; p=p->next; } cout<next; } return cnt; } T getHead() { if(head==NULL) throw "no head !"; return head->data; } T getTail() { 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) { Node* p=head; int pos=0; 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(0); if(pos==-1) return false; Node* p=getPointer(pos); p->data=n; return true; } private : Node* getPointer(int pos) { Node* p=head; for(int i=0;inext; } 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=getPointer(pos-1); Node* cur=pre->next; pre->next=cur->next; delete cur; } return true; } }; /* 栈类 */ class Stack { List l; public : void push(const T& t) { l.insert_front(t); } void pop() { l.erase(l.getHead()); } T top() { return l.getHead(); } bool empty() { return l.empty(); } int size() { return l.size(); } void clear() { l.clear(); } }; /* 队列类 */ class Queue { List l; public : void push(const T& t) { l.insert_back(t); } void pop() { l.erase(l.getHead()); } T front() { return l.getHead(); } T back() { return l.getTail(); } bool empty() { return l.empty(); } int size() { return l.size(); } void clear() { l.clear(); } }; void main() { //自己的测试代码 }
相关文章推荐
- 转载的标准文档:C语言实现一个简单的单向链表list
- C++异常机制的实现方式和开销分析 (大图,编译器会为每个函数增加EHDL结构,组成一个单向链表,非常著名的“内存访问违例”出错对话框就是该机制的一种体现)
- 给定一个单向链表L(N0,N1,N2,N3……),在不改变node值得情况下,来编程实现对链表重新排列 ,使得排序后的链表为(N0,Nn,n1,Nn-1,n2,Nn-2……)。
- C语言-------实现一个简单的单向链表
- C++利用链表模板类实现一个简易队列
- 手动实现单向链表跟双向链表的一个简单demo
- JavaScript实现的一个单向链表
- 用c语言+单向链表实现一个贪吃蛇
- 给定一个单向链表(长度未知),请设计一个既节省时间又节省空间的算法来找出该链表中的倒数第m个元素。实现这个算法,并为可能出现的特例情况安排好处理措施。“倒数第m个元素”是这样规定的:当m=0时,链表的
- 利用 C++ 单向链表实现队列
- 用单向链表实现队列功能
- Go实战--实现一个单向链表(The way to go)
- 单向链表 练习3.2 一个链表中的元素由另一个链表实现
- 实现一个链表和队列
- 自己动手构建无锁的并发容器(续篇)——基于单向链表实现的无锁队列
- java数据结构之LinkedQueue(用链表实现的双端单向队列)
- 用单向链表实现的一个管理系统
- 一个 while 实现 C 翻转单向链表
- C语言实现一个简单的单向链表list
- 使用内部单向链表实现的一个简单堆栈