文章

6

粉丝

47

获赞

0

访问

1.4k

头像
单链表 题解:我这个怎么不对,先把输入的数排序,然后用头插法插进链表,奔溃啊
P1015 贵州大学机试题
发布于2024年3月25日 16:41
阅读数 168


#include<iostream>
#include<stdio.h>
#include<algorithm>
#include<string.h>
#include<stdlib.h>
using namespace std;


int compare(const void *a,const void *b){
    return (*(int *)b-*(int *)a);
}

typedef struct node {
    int Element; // 节点中的元素为整数类型
    struct node * Next; // 指向下一个节点
}*Lin,node;

Lin create(int *arr){
    Lin p,L,head;
    head=new node;
    head->Next=NULL;
    L=head;
    for(int i=0;i<5;i++){
        p=new node;
        p->Element=arr[i];
        p->Next=L->Next;
        L->Next=p;
    }
    return head;
}

int main(){
    int arr[5];
    for(int i=0;i<5;i++)
       &...

登录查看完整内容


登录后发布评论

1 条评论
snake
2024年3月25日 22:13

有几个地方需要修改,如下:

#include<iostream>
#include<stdio.h>
#include<algorithm>
#include<string.h>
#include<stdlib.h>
using namespace std;


int compare(const void *a,const void *b){
    return (*(int *)b < *(int *)a);//这里!!!
}

typedef struct node {
    int Element; // 节点中的元素为整数类型
    struct node * Next; // 指向下一个节点
}*Lin,node;

Lin create(int *arr){
    Lin p,L,head;
    head=new node;
    head->Next=NULL;
    L=head;
    for(int i=0;i<5;i++){
        p=new node;
        p->Element=arr[i];
        p->Next=NULL;
        L->Next=p;//这里!!!
        L=p;//这里!!!
    }
    return head;
}

int main(){
    int arr[5];
    for(int i=0;i<5;i++)
        scanf("%d",&arr[i]);
    qsort(arr,5,sizeof(int),compare);
//    for(int i=0;i<5;i++)
//        printf("%d ",arr[i]);
//    cout<<endl;
    Lin L=create(arr);
    L=L->Next;

    while(L!=NULL){
        printf("%d ",L->Element);//这里!!!
        L=L->Next;
    }
    return 0;
}

 

赞(1)