这个链表的题帮我分析下,谢谢大家了
来源:百度知道 编辑:UC知道 时间:2024/05/25 06:40:11
struct node{
int x;
struct node *next;
}
struct node * create(int n)
{
struct node *p,*p1,*p2,*h=NULL; int i=0;
if(n<1) return NULL;
while(i<=n)
{
p=(struct node *) malloc(sizeof(struct node));
scanf(“%d”,&p->x);p->next=NULL;
if(h==NULL)h=p;
else
{p1=p2=h;
while(p2 &&p->x>=p2->x) {p1=p2;p2=p2->next;}
if(p2==h){p->next=p2;h=p;}
else{p->next=p2;p1->next=p;}
}
i++;
}
return h;
}
函数create的功能是:创建一个有序的链表(结点中x的值按升序排序),链表中结点的个数为参数n的值,函数返回该有序链表的头指针。算法思想如下:每产生一个新的结点,插入到链表中的恰当位置,使得插入新结点以后的链表仍然保持有序
我怎么觉得这是降序的排列。没搞懂
while(p2 &&p->x>=p2->x) {p1=p2;p2=p2->next;}
if(p2==h){p->next=p2;h=p;}
else{p
int x;
struct node *next;
}
struct node * create(int n)
{
struct node *p,*p1,*p2,*h=NULL; int i=0;
if(n<1) return NULL;
while(i<=n)
{
p=(struct node *) malloc(sizeof(struct node));
scanf(“%d”,&p->x);p->next=NULL;
if(h==NULL)h=p;
else
{p1=p2=h;
while(p2 &&p->x>=p2->x) {p1=p2;p2=p2->next;}
if(p2==h){p->next=p2;h=p;}
else{p->next=p2;p1->next=p;}
}
i++;
}
return h;
}
函数create的功能是:创建一个有序的链表(结点中x的值按升序排序),链表中结点的个数为参数n的值,函数返回该有序链表的头指针。算法思想如下:每产生一个新的结点,插入到链表中的恰当位置,使得插入新结点以后的链表仍然保持有序
我怎么觉得这是降序的排列。没搞懂
while(p2 &&p->x>=p2->x) {p1=p2;p2=p2->next;}
if(p2==h){p->next=p2;h=p;}
else{p
从while(p2 &&p->x>=p2->x) {p1=p2;p2=p2->next;}可以看出是升序,
当p2不为NULL,并且p->x >= p2->x时,p1指向p2,p2指向它的下一个
就是说,当p的x大于p2的x时,就用p1保存p2,再将p2定位到下一节点,
p的插入位置就是p1与p2的中间,则要插入的p节点的x的值一定比p1的x大
所以是升序