链表的有序插入
从小到大排序
根据指针获取当前id,并设置前指针,方便操作:
// test1107.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include "stdio.h" #include "memory.h" #include <string.h> #include <stdlib.h> #include "string.h" typedef struct LINK{ int id; LINK *next; }Link; typedef struct LL{ Link *root; int num; }Ll; void insert(Ll *l,int num); int main(){ Ll *ll = (Ll *)malloc(sizeof(Ll)); ll->num = 0; ll->root = NULL; insert(ll,5); insert(ll,2); insert(ll,20); insert(ll,1); insert(ll,100); Link *link = (Link *)malloc(sizeof(Link)); printf("%d",ll->root->id); link = ll->root->next; while(link != NULL){ printf("->%d",link->id); link = link->next; } getchar(); return 0; } void insert(Ll *l,int num){ Link * linkp = (Link *)malloc(sizeof(Link)); Link * current = (Link *)malloc(sizeof(Link)); Link * new_id = (Link *)malloc(sizeof(Link)); current = l->root; linkp = l->root; while(current != NULL && current->id<num){ linkp = current; current = current->next; } new_id->id = num; new_id->next = current; if(linkp == NULL){ l->root = new_id; }else if(num < l->root->id){ l->root = new_id; }else{ linkp->next = new_id; } }
从大到小排序
// test1107.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include "stdio.h" #include "memory.h" #include <string.h> #include <stdlib.h> #include "string.h" typedef struct LINK{ int id; LINK *next; }Link; typedef struct LL{ Link *root; int num; }Ll; void insert(Ll *l,int num); int main(){ Ll *ll = (Ll *)malloc(sizeof(Ll)); ll->num = 0; ll->root = NULL; insert(ll,5); insert(ll,2); insert(ll,20); insert(ll,1); insert(ll,5); insert(ll,100); Link *link = (Link *)malloc(sizeof(Link)); printf("%d",ll->root->id); link = ll->root->next; while(link != NULL){ printf("->%d",link->id); link = link->next; } getchar(); return 0; } void insert(Ll *l,int num){ Link * linkp = (Link *)malloc(sizeof(Link)); Link * current = (Link *)malloc(sizeof(Link)); Link * new_id = (Link *)malloc(sizeof(Link)); current = l->root; linkp = l->root; while(current != NULL && current->id>num){ linkp = current; current = current->next; } new_id->id = num; new_id->next = current; if(linkp == NULL){ l->root = new_id; }else if(num > l->root->id){ l->root = new_id; }else{ linkp->next = new_id; } }