//设计一个算法使其元素递增有序
#include <iostream>
#include <stdlib.h>
#include <cstdio>
typedef int ElemType;
using namespace std;
typedef struct LNode{
ElemType data;
LNode *next;
}LNode,*LinkList;
LinkList List_TailInsert(LinkList &L){//尾插法
int x;
L=(LinkList)malloc(sizeof(LNode));
LNode *s,*r=L;
scanf("%d",&x);
while(x!=999){
s=(LNode *)malloc(sizeof(LNode));
s->data=x;
r->next=s;
r=s;
scanf("%d",&x);
}
r->next=NULL;
return L;
}
LinkList Charu(LinkList &L){//直接插入法
LNode *p=L->next;LNode *pre;LNode *r=p->next;
p->next=NULL;
p=r;//当p->next时,r用来保存后面的链表
while(p!=NULL){
pre=L;
r=p->next;
while(pre->next!=NULL&&pre->next->data<p->data)
pre=pre->next;
p->next=pre->next;
pre->next=p;
p=r;
}
}
void print(LinkList L) {
printf("\n");
if(L->next==NULL)
printf("该链表为空");
LNode *p= L->next;
while(p!=NULL) {
printf("%d ",p->data);
p=p->next;
}
}
int main()
{
LinkList L1=NULL;
List_TailInsert(L1);
print(L1);
Charu(L1);
print(L1);
return 0;
}
有一个带头结点的单链表L,设计一个算法使其元素递增有序
于 2023-03-17 19:19:52 首次发布