顺序链表 不带头结点 c++

#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 = 0;
		}
		~LinkList()	{
			Node *p;
			while (head)	{
				p = head->next;
				delete head;
				head =p;
			}
		}
		bool IsEmpty()	const	{
			if (head)
				return false;
			else 
				return true;
		}

		int Length()const {
			int i= 0;
			Node *p =head;
			while (p)	{
					i++;
					p = p->next;
			}
			return i;
		}
		int Find(const int &elem)	const{
			int i =0;
			Node* p = head;
			while ( p )	{
				i++;
				if (p->data  == elem)
					return i;
			}
			return 0;
		}

		bool GetElem( int pos, int &m)	const	{
			int i = 1;
			Node * p =head;
			while (p && i< pos)	{
				i++;
				p= p->next;
			}
			if( !p ||  i>pos)	{
				cout<<" error"<<endl;
				return false;
			}
			m = p->data;
		}

		bool Insert (int pos ,const int & elem)	{
			int length = Length() ;
			if (pos <0  || pos > length )	{
					cout <<" input error"<<endl;
					return false;
			}
			Node * p = new Node;
			p->data = elem;
			if (pos == 1)	{ 				
				p->next = head;
				head =p;
			}
			else 	{
				int i =1 ;
				Node  * q = head ;
				while ( q && i< pos-1)	{
					i++;
					q =q->next;
				}				
				p->next =q->next ;
				q->next =p;
			}
			return true;
		}
	
		void Show()const {
			int length =Length();
			cout<< "Lentht =="<<length<<endl;
			Node * p =head;
			for (int i =0; i< length ;i++)	{
				cout << i+1<<" is " <<p->data<<endl;
				p = p->next;
			}
		}

		bool Delete(int pos ,int & elem) {
			int length = Length() ;
			if (pos <0  || pos > ( length + 1 ))	{
				cout <<" input error"<<endl;
				return false;
			}	
			Node * p = head ,*q ;
			if ( pos ==1 )	{
				elem = head->data;
				q = head ;
				head = head->next;
				delete q;
			}
			else	{
				int i =1 ;
				while (p->next && i<pos-1)	{
						p = p->next ;
						i++;
				}
				q = p->next;
				p->next = q->next;
				elem = q->data;
			
				delete q;
			}
			return true;
		} 
			
				
};


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(3,el);
	L.Show();

}
			
				
				
			
		

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值