对动态链表的创建不太熟悉的同学请看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;
}
2024年9月1日更新
存在两个主要问题,
首先是创建链表的时候,最后的p->next=NULL应该放在循环里面,否则当循环n=0的时候会直接段错误
第二是每个函数的p不需要额外的分配空间,直接用传入的地址即可。
#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 = NULL, *head = NULL;
for (int i = 0; i < n; i++) {
p = (struct node *)malloc(sizeof(struct node));
scanf("%d", &x);
p->data = x;
p->next = NULL; // 每次创建新节点时将next设为NULL
if (head == NULL) {
head = p;
} else {
q->next = p;
}
q = p;
}
return head;
}
void print_list(struct node *head) {
struct node *p;
for (p = head; p != NULL; p = p->next) {
printf("%d ", p->data);
}
printf("\n");
}
void sort_list(struct node *head) {
struct node *p, *q;
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;
for (p = head; p != NULL; p = p->next) {
if (x == p->data)
return p;
}
return NULL;
}
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\n", p->data);
else
printf("Value not found\n");
return 0;
}