顺序链表 带头结点的

#include <iostream>
using namespace std;

class LinkList;
class Node {
	friend class LinkList;
	private :
		int data;
		Node * next;
};



class LinkList	{
	private :
		Node * head;
	public:
		LinkList()	{
			head = new Node ;
			if (!head){
				cout <<" can't init List"<<endl;
				exit(0);
			}
			head->next =0;
		}
		~LinkList()	{
			Node * current ;
			while (  head)	{
				current =  head->next;
				delete head;
				head =current;
			}
			//head->next = 0;
		}
		bool IsEmpty()const {
			if (head->next)
					return false;
			else 
					return true;
		}

		int Length()	{
			int i = 0;
			Node * current = head->next;
			while( current)	{
				i++;
				current =current->next;
			}
			return i;
		}
	  int   Find( const int &elem) const	{
			int i = 0;
			Node *p = head->next;
			while (p)	{
				i++;
				if ( p->data == elem)	{
					return i ;
				}
				p=p->next;
			}
			return 0;
		}
	
		 bool GetElem (int pos ,int &elem)	{
			int i = 1;
			Node * p =head->next;
			while ( p && i< pos )	{
				i++;
				p =p->next;
			}
			if (!p || i>pos ){
				cout <<" error "<<endl;
				return false;
			}
			elem = p->data;
			return true;
		}
		
		bool Insert( int pos ,const int & elem)	{
			int i =0 ;
			Node * p =head;
			while ( p&& i <pos -1)	{
				i++ ;
				p = p->next;
			}
			if ( !p || i >pos -1)	{
				cout <<" Insert ERROR "<<endl;
				return false;
			}
			Node * q = new Node ;
			q->data = elem;
			q->next = p->next;
			p->next = q;
			return false;
		}

		bool Delete(int pos ,int &lem)	{
			int  i = 0;
			Node *p = head ;
			while ( p->next && i<pos -1)	{
					p =p->next;
					i++;
			}
			if( !p || i> pos-1)	{
				return false;
			}
			Node * q ;
			q = p->next;
			lem = q->data;
			p->next = q->next;
			delete q;
			return true;
		}

		void Show()	{
			int leng =Length();
			cout<< leng<<endl;
			Node * p =head->next;
			for (int i =0; i< leng ;i++)	{
				cout << i+1<<" is " <<p->data<<endl;
				p = p->next;
			}
			}
};

int main()
{
	LinkList  L ;
	L.Insert(1,3);
	L.Insert(2,5);
	L.Insert(1,7);
	//L.Insert(8,3);
	L.Insert(3,3);
	cout <<" Length "<< L.Length()<<endl;
	int el =5;
	cout<<" 5 is in"<<L.Find(el)<<endl;
	L.Show();
	cout<<"now delete"<<endl;
	L.Delete(1 ,el);
	L.Delete(2,el);
	L.Show();
}

			
		

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值