c - 创建整数列表并按升序打印它们的 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;
}
解决方案
简单的错字。将&符号更改为百分比:
从:
scanf("&d", &nodeData);
至:
scanf("%d", &nodeData);
推荐阅读
- python - 使用 Python 将混合列中的 GB 复杂转换为 TB
- amazon-sns - EventBridge 消息未发布到 SNS
- c# - DataGridViewComboBoxColumn 事件触发太多次
- google-sheets - 如何根据多个条件进行 VLOOKUP 并返回最新的行结果?
- outlook - Outlook 加载项不适用于 Windows 上的 IMAP
- dynamics-365 - 如何将数据从一个 Common Data Service 推送到另一个由记录状态更改触发的 CDS?
- sql - 基于数据的 Oracle Pivot 帮助
- asp.net-mvc - 找不到 HttpPostedFileBase Visual Studio 2019
- rust - rsmpi 'mpi = 0.5.4' 由于明显拼写错误的函数调用而无法编译
- ios - Swift hitTest:point withEvent 来检测子视图