文章
9
粉丝
289
获赞
4
访问
82.3k
#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
int data;
struct node *next;
}node;
//创建链表
node* createList(int num[], int length)
{
node *p, *head, *r;
//初始化头结点
head = (node *)malloc(sizeof(node));
head->next = NULL;
//r定义为尾指针
r = head;
//尾插法
for(int i=0; i<length; i++)
{
p = (node *)malloc(sizeof(node));
p->data = num[i];
p->next = NULL;
r->next = p;
r = p;
}
return head;
}
//链表排序(直接插入)
void sort(node *head)
{
node *p = head->next;
node *pre;
node *r = p->next;
p->next = NULL; //将链表分为两条独立的链
p = r;
//将p指向另一条链,比较大小后,在合适的位置插入到主链上
while(p!=NULL)
{
r = p->next;
pre = head; //pre每次都从头指针开始
while(pre->next!=NULL && pre->next->data < p->data)//关键,要用pre->next去判断
pre = pre->next;
p->next = pre->...
登录后发布评论
暂无评论,来抢沙发