【Pi Pilei】Computer one of data structure: create singly linked list in ascending order of data elements

【Pi Pilei】Computer one of data structure: create singly linked list in ascending order of data elements

Content highlights

Create a singly linked list in ascending order of data elements. In the process of creation, it is required that after each data element is inserted, the data elements in the linked list are arranged in ascending order, and the same data element is only required to be inserted once.

Source code

//上机一
#include<iostream>//上机实验1:升序排列,无重复
using namespace std;
class node
{
    
    
	int data;
	node *next;
	friend class list;
};
class list
{
    
    
public:
	node *head;
	list(){
    
    head=NULL;}
	void creat(int x)
	{
    
    
		int m=1;
		node *s=new node;
		s->data=x;
		s->next=NULL;
		node *p,*q;
		p=NULL;
		q=head;
		while(q!=NULL&&x>=q->data)//head不为空,同时x大于等于q->data
		{
    
    
			
			if(x==q->data)//q=head时x==head->data,(return)不进行后续操作;
				m=0;
			if(m!=0)
				p=q;
			q=q->next;
			
		}
		if(m!=0)
		{
    
    
		    if(p==NULL)//head==NULL,head=s
		    {
    
    
			    head=s;
		    }
		    else//head!=NULL时,根据下面两句 s成功连入
		    {
    
    
			    p->next=s;
		    }
		    s->next=q;
		}
	}
	void show()
	{
    
    
		node *p;p=head;
		while(p)
		{
    
    
			cout<<p->data<<' ';
			p=p->next;
		}
		cout<<endl;
	}
};
int main()
{
    
    
	list l;int x;
	cout<<"请输入数字,输0结束"<<endl;
	while(cin>>x&&x)
	{
    
    
		l.creat(x);
	}
	cout<<endl<<"输出:"<<endl;
	l.show();
}

Readme

This is the first time a rookie writes a blog. Go on! Put the code up as a souvenir hhhh~
Your likes and attention are all great encouragement to me!

Guess you like

Origin blog.csdn.net/qq_43704702/article/details/103744987