ZJGSU 1738 链表查找(线性表)(一些恶心的手搓链表题)

该文章描述了一个编程问题,要求在给定的非空线性链表中,不使用额外节点的情况下找到并移动数据域值最小的节点到链表的最前面。通过插入节点、遍历链表以及找到最小值的方法实现这一操作。
摘要由CSDN通过智能技术生成

已知非空线性链表由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);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值