建立单调有序链表的两种方法及具体操作

在这里插入图片描述

方法一:先建立链表,后对链表进行排序

#include <stdio.h>
#include <stdlib.h>
typedef struct LNode
{
    int data;
    struct LNode *next;
};
void creatListH(struct LNode *head, int n);//创建链表
void print(struct LNode *head);//输出链表
void list_sort(struct LNode *head);//链表排序
int main()
{
    struct LNode *head;
    int n;
    while(scanf("%d",&n)!=-1)
    {
        head= (struct LNode *)malloc(sizeof(struct LNode));
        if(!head)
            exit(0);
        head->next=NULL;
        creatListH(head,n);
        list_sort(head);
        print(head);
        printf("\n");
    }
    return 0;
}
/* 尾插法 */
void creatListH (struct LNode *head, int n)
{
    struct LNode *p1, *p2;
    int i;
    p2=head; //把尾赋给尾指针
    for(i = 0; i < n; i++)
    {
        p1 = (struct LNode *)malloc(sizeof(struct LNode));
        if(!p1)
            exit(0);
        scanf("%d",&(p1->data));
        p1->next = p2->next;
        p2->next = p1;
        p2 = p1; //插入的结点变为尾结点
    }
}
void print(struct LNode *head)
{
    struct LNode *p;
    p=head->next;
    if(head!=NULL)
        while(p)
        {
            printf("%d  ",p->data);
            p=p->next;/*指向下一个节点*/
        }
}
void list_sort(struct LNode *head)
{
    struct LNode *p1,*p2;
    int m;
    p1=head->next;
    while(p1!=NULL)
    {
        p2=p1->next;
        while(p2!=NULL)
        {
            if(p1->data>p2->data)
            {
                m=p1->data;
                p1->data=p2->data;
                p2->data=m;
            }
            p2=p2->next;
        }
        p1=p1->next;
    }
}

方法二:在插入时,就进行链表的排序

#include <stdio.h>
#include <stdlib.h>
typedef struct LNode
{
    int data;
    struct LNode *next;
};
void creatListH(struct LNode *head, int n);//创建链表
void print(struct LNode *head);//输出链表
void list_sort(struct LNode *head,int x);//链表排序
int main()
{
    struct LNode *head;
    int n;
    while(scanf("%d",&n)!=-1)
    {
        head= (struct LNode *)malloc(sizeof(struct LNode));
        if(!head)
            exit(0);
        head->next=NULL;
        creatListH(head,n);
        print(head);
        printf("\n");
    }
    return 0;
}
/* 尾插法 */
void creatListH (struct LNode *head, int n)
{
    int i,x;
    for(i = 0; i < n; i++)
    {
        scanf("%d",&x);
        list_sort(head,x);
    }
}
void print(struct LNode *head)
{
    struct LNode *p;
    p=head->next;
    if(head!=NULL)
        while(p)
        {
            printf("%d  ",p->data);
            p=p->next;/*指向下一个节点*/
        }
}
void list_sort(struct LNode *head,int x)
{
    struct LNode *p1,*p2,*q;
    p2=head;//p2是x插入位置的前驱结点
    p1=head->next;//首(链表第一个结点)结点
    while(p1!=NULL && p1->data<x)//查找位置
    {
        p2=p1;//前驱结点;
        p1=p1->next;//下一个结点
    }
    q=(struct LNode*)malloc(sizeof(struct LNode));
    q->data=x;
    q->next=p1;
    p2->next=q;
}

猜你喜欢

转载自blog.csdn.net/qq_46126537/article/details/106231484