Problem C: 链表插入(线性表)
Description
(线性表)已知一单向链表,从第二个结点至表尾递增有序,(设a1<x<an)如下图(“第二个结点至表尾”指a1..an )。试编写程序,将第一个结点删除并插入表中适当位置,使整个链表递增有序。
Input
输入长度n:7
输入数据:4 1 2 3 6 8 9
Output
1 2 3 4 6 8 9
Sample Input
5 11 7 8 9 10
Sample Output
7 8 9 10 11
HINT
#include <iostream>
#define NULL 0
using namespace std;
struct student
{
int num;
student *next;
};
int n;
student *creat(int m)
{
student *head,*p1,*p2;
p1=p2=new student;
cin>>p1->num;
head=NULL;
n=0;
while(p1->num!=NULL)
{
n=n+1;
if(n==1)head=p1;
else p2->next=p1;
p2=p1;
p1=new student;
if(n==m)
{break;}
else
cin>>p1->num;
}
p2->next=NULL;
return(head);
}
void print(student *head)
{
student *p;
p=head;
if(head!=NULL)
do
{
cout<<p->num<<" ";
p=p->next;
}while(p!=NULL);
}
student *intset(student *head)
{
student *p0,*p1,*p2;
p0=new student;
p0=head; //用p0来记录第一个数值,比较大小再插入
p1=head->next;
if(p0->next==NULL)
{
head=head;
}
else
{
if(p0->num<=p1->num)
head=head;
else
{
head=head->next;
while(p1->num<p0->num&&p1->next!=NULL)
{ p2=p1;
p1=p1->next;}
if(p1->num>p0->num)
{p2->next=p0;
p0->next=p1; }
else
{p1->next=p0;
p0->next=NULL;
}
}
}
return head;
}
int main()
{
int m,num;
cin>>m;
student *head,*stud;
student *creat(int);
void print(student *);
student *intset(student *);
head=creat(m);
head=intset(head);
print(head);
return 0;
}