C语言单链表的排序、查找(通俗易懂)

对动态链表的创建不太熟悉的同学请看https://blog.csdn.net/tongjingqi_/article/details/105831323
想了解单链表的增删改的同学请看
https://blog.csdn.net/tongjingqi_/article/details/105873529
本篇讲用选择法进行排序和顺序查找
利用选择法进行排序,每次交换数据,每一个位置(地址)的连接方式不改变,和数组排序同理,区别只是遍历方式不同,具体思想是:从先第一个位置开始遍历,只要后面的数比第一个数小就交换,所以第一次遍历结束后第一个位置存放最小数据,同理再从第二个位置继续遍历,最后第二个位置得到第二小的数据,以此类推,实现升序排列,降序同理。
顺序查找就是从前往后依次遍历链表,符合链表的结构,也容易理解
在这里插入图片描述
第一次输出排序结果,第二次输出查找‘3’的结果
代码如下

#include <stdio.h>
#include <stdlib.h>
struct node
{
    int data;
    struct node*next;
};
struct node* create_list(int n)//建立链表
{
    int x;
    struct node *p,*q,*head=NULL;
    for(int i=0;i<n;i++)
    {
        p=(struct node*)malloc(sizeof(struct node));
        scanf("%d",&x);
        p->data=x;
        if(head==NULL)
        {
           head=p;
        }
        else{
            q->next=p;
        }
        q=p;
   }
    p->next=NULL;
    return head;
};
void print_list(struct node* head)//输出链表
{
    struct node* p=(struct node*)malloc(sizeof(struct node));
    for(p=head;p!=NULL;p=p->next)
    {
        printf("%d ",p->data);
    }
    printf("\n");
}
void sort_list(struct node* head)//链表选择排序
{
    struct node *p=(struct node*)malloc(sizeof(struct node));
    struct node *q=(struct node*)malloc(sizeof(struct node));
    int t;
    for(p=head;p!=NULL;p=p->next)//选定的位置,从第一个位置开始
    {
        for(q=p->next;q!=NULL;q=q->next)//每次遍历一遍链表,只要比选定位置的数据小就交换
        {
            if(q->data<p->data)
            {
                t=q->data;
                q->data=p->data;
                p->data=t;
            }
        }
    }
}
struct node* find(struct node* head,int x)//顺序查找
{
     struct node *p=(struct node *)malloc(sizeof(struct node));
     for(p=head;p!=NULL;p=p->next)//从前往后遍历链表查找
     {
         if(x==p->data)
         return p;
     }
     return p;
}
int main()
{
    int n;
    struct node*head,*p;
    scanf("%d",&n);
    head=create_list(n);
    print_list(head);
    sort_list(head);
    print_list(head);
    p=find(head,3);
    if(p!=NULL)
    printf("%d",p->data);
    return 0;
}
  • 14
    点赞
  • 101
    收藏
    觉得还不错? 一键收藏
  • 8
    评论
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值