链表排序---冒泡法按值排序

本文详细介绍了一种链表排序算法的实现过程,利用冒泡排序法对链表中的数字进行排序,包括链表的创建、显示、长度计算、节点搜索及删除等功能,并通过示例代码展示了完整的操作流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本文是继上两篇之后的博客:主要展示对链表中的数字,使用冒泡法进行排序;

# include<stdio.h>
# include<math.h>
# include<stdlib.h>
using namespace std;
typedef struct node
{
	int data;
	struct node * next;
}Node;

Node * creat_list_first()
{
	Node * head = (Node *)malloc(sizeof(Node));
	head->next = NULL;
	
	int data;
	printf("请输入节点数据:\n");
	scanf("%d", &data);
	while (data)
	{
		Node * cur = (Node *)malloc(sizeof(Node));
		cur->data = data;
		cur->next = head->next;
		head->next = cur;
		scanf("%d", &data);
	}
	return head;
}

Node * insert_list_end()
{
	Node * head = (Node *)malloc(sizeof(Node));
	head->next = NULL;
	Node * phead = head;
	printf("请输入节点数字:\n");
	int data;
	scanf("%d", &data);
	while (data)
	{
		Node * cur = (Node *)malloc(sizeof(Node));
		cur->next = NULL;
		cur->data = data;
		phead->next = cur;
		phead = cur;
		scanf("%d", &data);
	}
	return head;
}
void show_list(Node * head)
{
	Node * p = head->next;
	while (p)
	{
		printf("%d\n", p->data);
		p = p->next;
	}
}
int len_list(Node *head)
{
	Node * phead = head->next;
	int count = 0;
	while (phead)
	{
		count++;
		phead = phead->next;
	}
	return count;
}
int search_node_loc(Node * head, int search_data)
{
	Node * phead = head->next;
	int loc = 1;
	while (search_data != phead->data)
	{
		loc++;
		phead = phead->next;
	}
	return loc;
}
Node * search_node_dizhi(Node * head,int search_data)
{
	Node * phead = head->next;
	while (phead)
	{
		if (phead->data == search_data)
		{
			break;
		}
		phead = phead->next;
	}
	return phead;
}
void delete_node(Node * head, Node * delete_node)
{
	Node * loc = delete_node;
	while (head->next != loc) head = head->next;//此处说明是待查找数据的前一项节点;
	head->next = loc->next;
}
void pop_sort(Node*phead, int len)
{
	Node * cur = NULL;
	int temp = 0;
	for (int i = 0; i < len - 1; i++)
	{
		cur = phead->next;
		for (int j = 0; j < len - 1 - i; j++)
		{
			if (cur->data > cur->next->data)
			{
				temp = cur->data;
				cur->data = cur->next->data;
				cur->next->data = temp;
			}
			cur = cur->next;
		}
	}
}


int main()
{
	Node * head = insert_list_end();
	show_list(head);
	printf("链表长度:%d\n", len_list(head));
	printf("查找数据在%d\n", search_node_loc(head, 4));
	delete_node(head, search_node_dizhi(head, 4));
	show_list(head);
	printf("after pop sort \n");
	pop_sort(head, len_list(head));
	show_list(head);

	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

嘟嘟love佳

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值