单链表排序问题
单链表排序,最简单的,只进行数值排序,就像数组,而不换地址,要怎样实现,求教
申请节点啊 跟数组排序一样的 只不过操作复杂一点 ,需要注意的细节多一点 ,,冒泡就能完成
程序代码:#include <stdio.h>
#include <stdlib.h>
struct node
{
int n;
struct node* next;
};
//注意在这里最后一个节点p->next=NULL
struct node* create()
{
struct node* p;
struct node* head;
int i=0;
struct node* q=(struct node*)malloc(sizeof(struct node));
q->n=0;
head=q;
for(;i<10;i++)
{
p=(struct node*)malloc(sizeof(struct node));
p->n=i+1;
q->next=p;
q=p;
}
q->next=NULL;
return head;
}
void swap(struct node* p,struct node* q)
{
int tmp;
//仅交换数值,节点不变
tmp=p->n;
p->n=q->n;
q->n=tmp;
}
void print(struct node* head)
{
struct node* p=head;
for(;p->next!=NULL;p=p->next)
{
printf("%d ",p->n);
}
}
int main()
{
struct node* head=create();
struct node* p;
struct node* q;
//p->next!=NULL决定了最后一个节点虽有数字,但不会被使用,要想被使用,就得额外增加一个空节点
for(p=head;p->next!=NULL;p=p->next)
{
for(q=p->next;q->next!=NULL;q=q->next)
{
if(p->n<q->n)
{
swap(p,q);
}
}
}
print(head);
return 0;
}

程序代码:struct node* create()
{
struct node* p;
struct node* head;
int i=0;
struct node* q=(struct node*)malloc(sizeof(struct node));
q->n=0;
head=q;
for(;i<10;i++)
{
p=(struct node*)malloc(sizeof(struct node));
p->n=i+1;
q->next=p;
q=p;
}
/*****临时节点*****/
p=(struct node*)malloc(sizeof(struct node));
q->next=p;
p->n=-1;
p->next=NULL;
/*****临时节点*****/
return head;
}
