C++:按数字排序链表错误
C++: Sorting linked list in order by number error
我正在读取的文件看起来像这样:
吨 44
C 13
一 47
19
克 41
N 51
. 4
以此类推,总共有53行。我需要阅读这些行并使用 addInOrder 函数将它们按顺序排列。我用cout做了一个测试,我看到
字母= t, 数字= 44, head= 44
字母= c, 数字= 13 , head= 13
字母= a , 数字= 47 , 头= 13
字母: [空格] , 数字= 19 , 头部= 13
字母: g , 数字= 41 , 头= 13
字母: n , 数字= 51 , 头= 13
字母: . , 数字= 4 , 头= 13
直到稍后 num = 12 时,头部才会改变,然后在 num = 1 时再次更改。
当我最后打印时,链表按第一个数字而不是整数排序,它遵循以下顺序:
- 1
- 10
- 11
- 。
- 19
- 阿拉伯数字
- 20
- 21
- 。
- 29
- 3
- 30
- 31
等等...我需要它是:
- 1
- 阿拉伯数字
- 3
- 。
- 9
- 10
- 11
addInOrder 函数的逻辑中是否存在错误?
这是我的主要:
#include <fstream>
#include <iostream>
#include <string>
#include <sstream>
#include <stdio.h>
#include <ctype.h>
using namespace std;
struct ListNode
{
string letter;
string num;
ListNode *next;
};
void addInOrder(ListNode *&h, string l, string n);
void printList(ListNode *h, int &lengthOfFile);
void deleteList(ListNode *&h);
int main()
{
string letter;
string num;
string lines;
int lengthOfFile = 0;
const string FILENAME = "link to file";
ifstream inFile(FILENAME);
ListNode *head = nullptr;
if (inFile)
{
string line;
for (int lineNum = 1; getline(inFile, line); lineNum++)
{
stringstream ss(line);
string word;
for (int wordNum = 1; ss >> word; wordNum++)
{
if (wordNum == 1)
{
char c = word[0];
if (isalpha(c))
{
letter = c;
}
else if (word == "!" or word == ".")
{
letter = word;
}
else if (word != "!" or word != ".")
{
letter = " ";
num = word;
lengthOfFile++;
if (wordNum == 1)
{
addInOrder(head, letter, num);
}
}
}
if (wordNum == 2)
{
num = word;
lengthOfFile++;
}
if (wordNum == 2)
{
addInOrder(head, letter, num);
}
}
}
inFile.close();
}
printList(head, lengthOfFile);
deleteList(head);
}
这是我按数字顺序添加到链表中的函数:
void addInOrder(ListNode *&h, string l, string n)
{
ListNode *newNode;
newNode = new ListNode;
newNode->letter = l;
newNode->num = n;
if (h == nullptr)
{
h = newNode;
newNode->next = nullptr;
}
else
{
ListNode *prev = nullptr;
ListNode *curr = h;
while ((curr != nullptr) && (curr->num < n))
{
prev = curr;
curr = curr->next;
}
if (prev == nullptr)
{
h = newNode;
newNode->next = curr;
}
else
{
prev->next = newNode;
newNode->next = curr;
}
}
}
打印列表以确保索引:
void printList(ListNode *h, int &lengthOfFile)
{
ListNode *ptr = h;
for(int i = 0; i < lengthOfFile; i++)
{
cout << ptr->letter << " ";
cout << ptr->num << " ";
cout << endl;
ptr = ptr->next;
}
cout << endl;
}
删除列表:
void deleteList(ListNode *&h)
{
ListNode *ptr;
while (h != nullptr)
{
ptr = h;
h = h->next;
delete ptr;
}
}
您正在比较string
,而不是数字。列表按字母顺序正确排序。
如果要按数字顺序排序,则必须将字符串转换为整数(或任何其他数值(。
相关文章:
- 错误:需要类名(链表c++)
- 链表错误的中间
- 奇怪的C++链表错误
- C++:按数字排序链表错误
- 双向链表错误
- 第一次运行程序时出现损坏的双链表错误,后续运行正常
- c++:链表错误" Access violation reading location"
- 链表错误
- 链表错误无限循环
- C++glibc检测到损坏的双链表错误C++
- 合并两个排序的单向链表 [错误]
- 将对象添加到链表错误 [C++]
- 链表错误:语法错误:标识符'head'之前缺少';'
- 带有队列LNK2005的链表错误
- 打印链表错误。怎么了?
- 有序链表错误
- 从开始内存中删除链表错误
- 由模板类型转换的链表错误
- 双链表错误实现Deque
- 机器相关的损坏的双链表错误