论坛首页 编程语言技术论坛

一个单向链表,并实现栈和队列

浏览 2748 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2008-07-15  
C
以下是本人学习中写的一个简单的链表和棧以及队列的实现,由于时间问题没有注释,但命名都很直观.

#include <iostream>
using namespace std;
#include <string>

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<<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 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;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=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()
{
//自己的测试代码
}


很多不足之处正在慢慢探索学习中。
论坛首页 编程语言技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics