已知非空线性链表由list指出,链结点的构造为(data,link).请写一算法,将链表中数据域值最小的那个链结点移到链表的最前面。要求:不得额外申请新的链结点
输入样例 1 点击复制
5 11 6 8 7 9
输出样例 1
6 11 8 7 9
思路:
先创建链表,然后在输入的时候找出最小值,再遍历链表,当某个节点的值与最小值相等时,将这个节点移到链表最前端
#include<stdio.h>
#include<stdlib.h>
const int inf=0x3f3f3f3f;
struct node{
int data;
struct node*next;
};
void insert(struct node*p,int a)//插入新节点
{
while(p->next!=NULL)p=p->next;
struct node*cur;
cur=(struct node*)malloc(sizeof(struct node));
if(cur==NULL)return;
cur->data=a;
p->next=cur;
cur->next=NULL;
}
void solve(struct node*head,int min)//将最小值移到链表最前端
{
struct node*cur;
struct node*pre;
pre=head;
cur=head->next;
while(cur!=NULL)
{
if(cur->data==min)//找到最小值,移到链表最前面
{
pre->next=cur->next;
cur->next=head->next;
head->next=cur;
return;
}
cur=cur->next;
pre=pre->next;
}
}
void print(struct node*head)//输出链表
{
head=head->next;
while(head!=NULL)
{
printf("%d ",head->data);
head=head->next;
}
return;
}
int main()
{
int n;
scanf("%d",&n);
struct node*head;
struct node*p;
head=(struct node*)malloc(sizeof(struct node));
p=head;
head->next=NULL;
if(head==NULL)return 0;//创建链表头结点
int min=inf;
for(int i=0;i<n;i++)
{
int a;
scanf("%d",&a);
insert(p,a);
if(a<min)min=a;//找出最小值
}
solve(head,min);
print(head);
}