C++单链表的基本操作的实现

#ifndef _SINGLE_LIST_H_
#define _SINGLE_LIST_H_
class Node
{
public:
	int data;
	Node *next;
	Node(int val=0):data(val),next(NULL){}
};
class LinkList
{
public:
	LinkList()
	{
		head=new Node;
		head->next=NULL;
	}
	void Create_Rear(int n)//尾插法建立单链表
	{
		Node *p=head;
		Node *temp;
		int i,value;
		for(i=0;i<n;i++)
		{
			cin>>value;
			temp=new Node(value);
			p->next=temp;
			p=temp;
		}
	}
	void Create_Front(int n)//头插法建立单链表
	{
		Node *temp,*p=head;
		int i,value;
		for(i=0;i<n;i++)
		{
			cin>>value;
			temp=new Node(value);
			temp->next=p->next;
			p->next=temp;
		}
	}
	//该函数可以实现在带头节点的单链表中的任意位置插入节点
	void Insert(int i,int val)//在i位置处插入元素为val的节点
	{
		//i: 1,2,3,4,5................
		Node *p=head;
		int j=0;
		while(p!=NULL && j<i-1) //定位第i-1个节点
		{
			p=p->next;
			j++;
		}
		if(!p || j>i-1)
		{
			cout<<"插入位置i非法!!!"<<endl;//无法找到第i-1个节点
		}
		else
		{
			Node *s = new Node(val);
			s->next=p->next;
			p->next=s;
		}
	}
	///////////////////////////////////////////////////////
	void DeleteNode(int i)/* i= 1 2 3 4*/
	{
		int j=0;
		Node *p=head;
		while(p && j<i-1)//p指向第i-1个节点
		{
			p=p->next;
			j++;
		}
		if(!p || !p->next)        //     (!p || j>=i-1)
		{
			cout<<"删除位置错误"<<endl;
		}

		else
		{
			Node *cur=p->next;
			p->next=cur->next;
			delete cur;
			cur=NULL;
		}

	}
	
	//删除指定节点
	void Delete(int value)
	{
		Node *p=head->next;
		Node *q;
		if(p==NULL)
			return ;
		if(p->data==value)//删除第一个节点
		{
			head->next=p->next;
			delete p;
			p=NULL;
		}
		else
		{
			while(p->data!=value &&p->next!=NULL)//循环结束时 p指向被删除节点
			{
				q=p;
				p=p->next;
			}
			if(p->data==value)
			{
				q->next=p->next;
				delete p;
				p=NULL;
			}
			else
			{
				cout<<"该节点不存在!!!"<<endl;
				return ;
			}
		}

	}

	//删除倒数第k个节点
	void Delete_k(int k)
	{
		Node *p=head->next;
		Node *q=head->next;
		int i=1;
		while(i<=k&&p->next)
		{
			p=p->next;
			i++;
		}
		if(p->next==NULL)//这个判断是必须的
			return ;
		while(p->next!=NULL)
		{
			p=p->next;
			q=q->next;
		}
		//q指向倒数第k+1个节点
		Node *s=q->next;
		q->next=s->next;
		delete s;
		s=NULL;
	}

	//链表的倒置
	//改变源链表的结构
	//用三个指针
	void Reverse1()
	{
		Node *pf=head->next;
		Node *cur=pf->next;
		Node *pb=cur->next;
		head->next=NULL;
		pf->next=NULL;
		while(pb)
		{
			cur->next=pf;
			pf=cur;
			cur=pb;
			pb=pb->next;
		}
		cur->next=pf;
		head->next=cur;
	}
	//用两个指针
	void Reverse2()
	{
		Node *p=head->next;
		Node *r=NULL;
		head->next=NULL;
		while(p)
		{
			r=p->next;
			p->next=head->next;
			head->next=p;
			p=r;
		}
	}
	void print() const
	{
		Node *p=head->next;
		while(p)
		{
			cout<<p->data<<" ";
			p=p->next;
		}
		cout<<endl;
	}
private:
	Node *head;
};
#endif

猜你喜欢

转载自blog.csdn.net/Henry313/article/details/90080139