首页 > 解决方案 > 创建整数列表并按升序打印它们的 C 程序

问题描述

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

#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;
} 

这是程序编译输出的图像

标签: c

解决方案


简单的错字。将&符号更改为百分比:

从:

scanf("&d", &nodeData);

至:

scanf("%d", &nodeData);

推荐阅读