List node

#include<iostream>
using namespace std;

struct node
{
	int data;
	node *next;
};
class List
{
public:
	List();
	List(List &L);
	~List();
	void insert(const int);
	bool IsEmpty();
	size_t ListLen();
	int GetElem(size_t);
	void append(size_t,int);//在第i个位置插入数值
	void Display();
	void remove(size_t);
	int FindElem(int elm);
	void merge(List &L);
    node* GetFN();
	node* GetEN();
private:
	node *p;
};
List::List()
{
	p = new node;
	p->next = NULL;
}
//这里还是有问题的
List::List(List &L)
{
	p = L.GetFN();
}
List::~List()
{
	delete p;
}
node* List::GetFN()
{
	return p;
}
node* List::GetEN()
{
	node *q = p->next, *pre = q;
	while (q)
	{
		pre = q;
		q = q->next;
	}
    return pre;
}
void List::insert(const int a)
{
	node *q = p;
	while (q->next)
	{
		q = q->next;
	}
	node *m = new node;
	m->data = a;
	m->next = NULL;
	q->next = m;
}
void List::Display()
{
	node *q = p->next;
	while(q)
	{
		cout << q->data << " ";
		q = q->next;
	}
	cout << endl;
}
bool List::IsEmpty()
{
   node *q = p->next;
   return q==NULL?1:0;
}
size_t List::ListLen()
{
	if(IsEmpty())
		return 0;
	node *q = p->next;
	size_t i = 0;
	while (q)
	{
		++i;
		q = q->next;
	}
	return i;
}
int List::GetElem(size_t i)
{
	node *q = p->next, *pre = q;
	while (i--)
	{
		if(!q)
		  throw runtime_error("error"); 
		pre = q;
       q = q->next;
	}
	return (*pre).data;
}
void List::append(size_t i,int a)
{
	node *q = p->next, *pre = q;
	while (i--)
	{
		if(!q)
			throw runtime_error("error"); 
		pre = q;
		q = q->next;
	}
	node *m = new node;
	m->data = a;
	m->next = q;
	pre->next = m;
}
void List::remove(size_t i)
{
	node *q = p->next, *pre = q;
	while (--i)
	{
		if(!q)
			throw runtime_error("error"); 
		pre = q;
		q = q->next;
	}
    pre->next = q->next;
	delete q;
}
void List::merge(List &L)
{
   this->GetEN()->next = L.GetFN()->next;
}
int List::FindElem(int elm)
{
	node *q = p->next, *pre = q;
	int i = 0;
	while (q)
	{
		++i;
	    if((*q).data == elm)
			return i;
		pre = q;
		q = q->next;
	}
    if(q == NULL)
		throw runtime_error("can't find");  
}
int main()
{
	List l,m;
	l.insert(1);
	l.insert(12);
	l.insert(10);
	l.Display();
	m.insert(0);
	m.insert(-90);
	m.Display();
	l.merge(m);
	l.Display();
    cout << endl;
	//cout << l.GetElem(3);
}


你可能感兴趣的:(List node)