链式存储的直接插入排序

#include<stdio.h>
#include<malloc.h>

typedef int ElemType;
typedef struct Node
{
    ElemType data;
    struct Node *next; 
    /* data */
}Node,*LinkList;



//头插法
void head_creat_list(LinkList *p, int n){
    //n是容量
    
    *p = (Node *)malloc(sizeof(Node));
    
    
    (*p)->next = NULL;

    int i;
    for(i=1; i<=n; ++i){
        Node *q = (Node *)malloc(sizeof(Node));
        scanf("%d",&q->data);
        q->next = (*p)->next;
        (*p)->next = q;
    }
}



void insert_sort(LinkList *p, LinkList *new){
	//创建新链表头结点
	*new = (Node *)malloc(sizeof(Node));
    (*new)->next = NULL;

	Node *q = (*p)->next;

	while(q){
		Node *loc,*pre; 
		loc = (*new)->next;
		if((*new)->next == NULL || loc->data > q->data){
			Node *s =(Node *)malloc(sizeof(Node));
			s->data = q->data;
			s->next = (*new)->next;
			(*new)->next = s;
		}
		else{
			pre = loc->next;
			//loc指向当前节点
			//pre指向后一个节点
			
			while (pre && pre->data < q->data)
			{
				loc = pre;
				pre = pre->next;
			}
			Node *s =(Node *)malloc(sizeof(Node));
			s->data = q->data;
			s->next = pre;
			loc->next = s;
		}
		q = q->next;
	}
}
			

void show(LinkList *p){

    //第一个数据节点
    Node *q = (*p)->next;
    while(q){
        printf("%3d",q->data);
        q = q->next;
    }
    printf("\n");
}


int main(){
	LinkList list1;
	LinkList list2;
	head_creat_list(&list1,6);
	printf("排序前:");
	show(&list1);
	insert_sort(&list1,&list2);
	printf("排序后:");
	show(&list2);
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值