数据结构实验之链表六:有序链表的建立

来源:互联网 发布:车铣中心自动编程 编辑:程序博客网 时间:2024/05/16 06:11


这道题的算法思想就是通过比较已经建好链表中的元素,排序的同时建立新的单链表。

代码如下:

#include <stdio.h>
#include <malloc.h>
struct node{
    int data;
    struct node* next;
};
struct node* Createlist(int n){/*建立顺序单链表*/
    struct node* head,*tail,*p;
    int i,d;
    head=(struct node*)malloc(sizeof(struct node));
    head->next=NULL;
    tail=head;
    for(i=1;i<=n;i++){
        p=(struct node*)malloc(sizeof(struct node));
        scanf("%d",&d);
        p->data=d;
        p->next=NULL;
        tail->next=p;
        tail=p;
    }
    return head;
};
struct node* Paixulist(struct node* head){/*比较元素的大小,然后赋值,建立一个新的单链表*/
    struct node* head1,*tail,*p,*L;
    int d;
    head1=(struct node*)malloc(sizeof(struct node));
    head1->next=NULL;
    tail=head1;
    while(head){
        L=head->next;
        while(L){
            if(head->data<L->data)
                L=L->next;
            else{
                d=head->data;
                head->data=L->data;
                L->data=d;
                L=L->next;
            }
        }
        p=(struct node*)malloc(sizeof(struct node));
        p->data=head->data;
        p->next=tail->next;
        tail->next=p;
        tail=p;
        head=head->next;
    }
    return head1;
};
int main(){
    int n;
    struct node* head,*p;
    head=(struct node*)malloc(sizeof(struct node));
    p=(struct node*)malloc(sizeof(struct node));
    head->next=NULL;
    scanf("%d",&n);
    head=Createlist(n);
    p=head->next;
    head=Paixulist(p);
    for(p=head->next;p!=NULL;p=p->next){
        if(p==head->next)
            printf("%d",p->data);
        else
            printf(" %d",p->data);
    }
    return 0;
}

0 0
原创粉丝点击