题目:有一个带头节点的单链表L(节点个数大于1),其中ElemType类型为int,设计一个算法使其递增有序
分析:
先构造一个只有头节点和开始数据节点的有序表(只含有一个数据节点的单链表一定是有序的),遍历原单链表余下的节点,知道p==NULL为止,通过比较pre指针下一个节点的数值大小和p节点的大小关系来确定p所插入的位置。方法思想来源于直接插入排序。
方法的空间复杂度为O(1)
#include<stdio.h> #include<stdlib.h> typedef struct node{ int data; struct node *next; }Node; void creat_LinkList(Node *L,int value[],int n) { Node *rear=L; //尾插法 for(int i=0;i<n;i++) { Node *s=(Node *)malloc(sizeof(Node)); s->data=value[i]; s->next=NULL; rear->next=s; rear=s; } } void print(Node *L) { Node *p=L->next; while(p!=NULL) { printf("%d ",p->data); p=p->next; } printf(" "); } void insert_order(Node *L) { Node *p=L->next;//定义带有效数据的首节点为p L->next=NULL;//切断头节点和后面节点的连接,使头节点成为一个新的链表 Node *after_p=NULL;//定义一个p之后的节点为after_P,便于循环 while(p!=NULL)//插入排序 { after_p=p->next; Node *pre=L;//让pre指针沿着新的链表循环,方便比对大小 while(pre->next!=NULL&&pre->next->data<p->data)//p的节点大于pre所指的节点的数值时,pre后移 pre=pre->next; p->next=pre->next;//头插法插入p节点 pre->next=p; p=after_p; } } int main(){ int a[]={1,7,6,3,5,2,4,8}; int n=8; Node L={1000,NULL}; creat_LinkList(&L, a, n); insert_order(&L); print(&L); }