首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >创建整数列表并按升序打印它们的C程序

创建整数列表并按升序打印它们的C程序
EN

Stack Overflow用户
提问于 2020-11-02 16:46:05
回答 1查看 57关注 0票数 0

你好,我正在做一个关于链表的程序,它存储了一个整数列表,并按升序排序。一旦我输入了所有需要排序的整数,它只打印出第一个整数,我就有点卡在这部分了。有人能帮我吗?

代码语言:javascript
复制
#include <stdio.h>
#include <stdlib.h> 

struct node {
    int data;
    struct node *next;
}; struct node *first;


void createLinkedList (int nodes){
    int nodeData, j;
    struct node *tail;
    struct node *current;
    
    
    first = (struct node*)malloc(sizeof(struct node));
    
    if (first == NULL){
        printf("There's an error allocating memory.");
    }
    else{
        printf("Input the elements in the linked list: \n");
        scanf("%d", &nodeData);
        
        first->data=nodeData;
        first->next=NULL;
        current=first;
        
        for (j=2; j<=nodes; j++){
            tail = (struct node*)malloc(sizeof(struct node));
            
            if (tail == NULL){
                printf("There's an error allocating memory.");
                break;
            }
            else{
                scanf("&d", &nodeData);
                
                tail->data=nodeData;
                tail->next=NULL;
                current->next=tail;
                current=current->next;
            }
        }
    }   
}

void sortLinkedList (int nodes){
    int i, j, nodeDataCopy;
    struct node *current;
    struct node *nextNode;
    
    for (j=nodes-2; j>=0; j--){
        current=first;
        nextNode=current->next;
        
        for (i=0; i<=j; i++){
            
            if (current->data > nextNode->data){
                nodeDataCopy=current->data;
                current->data=nextNode->data;
                nextNode->data=nodeDataCopy;
            }
            
            current=nextNode;
            nextNode=nextNode->next;
        }
    }
}

void displayLinkedList(){

    struct node *current;
    
    current=first;
    
    while (current != NULL){
        printf("%d\n", current->data);
        current=current->next;  
    }
}

int main (){
    int nodes;
    
    first=NULL;
    
    printf("Input the number of elements in the linked list:\n ");
    scanf("%d", &nodes);
    
    createLinkedList (nodes);;
    sortLinkedList (nodes);
    
    printf("Sorted order:\n");
    displayLinkedList();
    
    return 0;
} 

Here's an image of the compiled output of the program

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-11-02 17:12:41

简单的打字错误。将与号更改为百分比:

发自:

代码语言:javascript
复制
scanf("&d", &nodeData);

至:

代码语言:javascript
复制
scanf("%d", &nodeData);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64642318

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档