简单的有序链表的建立

//此有序链表是双向的且输入为0时结束如1 2 3 5 0,但是排序时是不排0的
//并且输出是是没有0的,0只是结束标志
#include<iostream>
using namespace std;
struct node{
	int num;
	node *next,*pro;
};
node *head,*p,*q,*e;
//向头后第一个节点前插入的函数
void cha1(node *he,node *pc){
	he->next->pro=pc;
	pc->next=he->next;
	pc->pro=he;
	he->next=pc;
}
//向某个节点前插入节点
void cha2(node *find,node *pc){
	find->pro->next=pc;
	pc->pro=find->pro;
	pc->next=find;	
	find->pro=pc;
}
//向最后插入节点
void cha3(node *final,node *pc){
	final->next=pc;
	pc->pro=final;
	pc->next=NULL;
}
int main(){
	int i=0;
	//建立头结点(头结点并没有值,为了方便)
	head=new node;

	p=new node;
	//在外部先将一个结点与头结点链接
	head->next=p;
	p->pro=head;
	p->next=NULL;
	//输入新建结点的值
	cin>>p->num;
	//如果一开始是0,则直接结束
	if(p->num==0)return 0;

	q=p;

	while(1)
	{
	int flag1=1,flag2=1;//建立标志,如果走了cha1就不走cha2和cha3,后两个同理
	
	p=new node;
	p->pro=NULL;
	p->next=NULL;
	cin>>p->num;

	if(p->num==0)break;//是0则跳出

if(head->next->num>p->num)
{
	flag2=0;
	cha1(head,p);
}
else 
{
	e=head->next;
	while(e)
	{
		if(e->num>p->num)
		{
		flag1=0;
		cha2(e,p);
		break;//此处的bread我觉得是重点记的,插完一定要出去
		}
	e=e->next;
	}
}
if(flag1==1&&flag2==1)//如果cha1和cha2都没有插入的话
{
	e=head->next;
	while(e->next){
		e=e->next;
	}
	cha3(e,p);
}
}
	e=head->next;
	while (e)
	{
		cout<<e->num<<" "; 
		e=e->next;
	}
}

记得按0哦!!!!!!!!!!!!!!!!!!!!!!

猜你喜欢

转载自blog.csdn.net/weixin_43732022/article/details/88400386
今日推荐