C++实现单向链表的“建立”,“插入”,“删除”,“输出”

直接上代码

#include <iostream>
using namespace std;
struct data     
{
	int number;
	data *next;
};
data *head=NULL;  //定义一个全局变量的头指针 
void create()     //链表创造函数 
{
	data *p;data *s;int num;
	cout<<"please enter the num\n";
	while(cin>>num&&num)//以0为输出结束标志符  
	{
		s=new data;
		s->number=num;
		if(head==NULL)
		{
			head=p=s;
		}
		else p->next=s;
		p=s;	
	}
	p->next=NULL;//将链表的尾部设置为指向空节点 
}
void output()//链表输出函数 
{
	cout<<"The linked list which you create is\n";
	if(head==NULL)
    cout<<"The linked list which you create is empty\n";
	data *p=head;
	while(p!=NULL)
	{
		cout<<p->number<<' ';
		p=p->next;
	}
	cout<<'\n';
}
void insert()    //链表插入函数,函数的插入方式为从小到大; 
{
	int num;//你想插入的数字 
	data *p=head,*q;
	cout<<"please enter the number which you want to char\n";
	cin>>num;
	data *s=new data;//用一个外来的节点来存储这个数字,再将这个数字插入到链表中 
	s->number=num;
	while(s->number>p->number&&p->next!=NULL)//通过循环遍历来找到插入节点的位置:默认为从小到大插入 
	{                                        //跳出该循环有两种情况 1:要插入的数字不大于链表中的一个数了 
		q=p;                                 //2:已经到链表的末尾了 
		p=p->next;
	}
	if(s->number>p->number)                 //这对应于第二种情况 作业将该节点插入到链表的末尾 
	{
		p->next=s;
		s->next=NULL;
	}
	else
	{                                     //对于第一种情况也有两种可能 1:可能要插入的节点比头结点还要小 
		if(s->number<=head->number)       //2:比链表中间的某个数要小 
		{
			s->next=head;
			head=s;
		}
		else                            //这对应于情况一的第二种可能 
		{
			q->next=s;
			s->next=p;
		}
	}
//	delete s; 
	output();
}
void deletenum1()    //该删除函数为一个按值删除函数,且每次只能删除一个值 
{
	int num;
	cout<<"please enter the number which you want to delete\n";
	cin>>num;
	data *p=head,*q;
	while(p->number!=num&&p->next!=NULL)
	{
		q=p;
		p=p->next;
	}
	if(num==p->number)
	{
		if(head->number==num)
		head=head->next;
		else
		{
			q->next=p->next;
		}
	}
	else cout<<"There is no number which you want to delete\n";
	output();
}
void deletenum2()//该函数也为 一个按值 删除函数,但一次性能把所有同样的值删除 
{
	int num;
	cout<<"please enter the number which you want to delete\n";
	cin>>num;
	data *p=head;
    while(p!=NULL&&p->next!=NULL)
    {
    	if(p->next->number==num)
    	{
    		if(p->next->next!=NULL)
    		p->next=p->next->next;
    		else
    		p->next=NULL;	
		}
		else
		p=p->next;
	}
	p=head;             //当头结点也为该值时单独处理 
	if(p->number==num)      
    head=p->next;
	output();
}
void deletelist()//链表删除函数,在程序结束的时候一定要调用此函数,否则会造成内存泄漏
{
	data *p=head,*s;
	while(p->next!=NULL)
	{
		s=p;
		p=p->next;
		delete s;
	}
	delete p;
	head=NULL;
	output();
}
 
int main()
{
	create();//如果你想重新创建一个链表请将头结点设置为一个空节点 
	output();
	insert();
	deletenum1();
	deletenum2();
	deletelist();
} 
//1 1 3 3 3 5 7 9 0

猜你喜欢

转载自blog.csdn.net/achenjie/article/details/81087880
今日推荐