C++ 按升序将整数插入链表

C++ 按升序将整数插入链表,c++,linked-list,C++,Linked List,我试图在链表中按升序插入一个新元素,我输入3,1,9,7,5的代码输出1,1,1,1,1,1,1,但是我想要的输出是1,3,5,7,9 head实际上位于类列表的私有实例变量中,这是一个成员函数 它被称为: 列表a a.insertinoder(3);a、 插入诺德(1);a、 插入诺德(9);a、 插入诺德(7);插入诺德(5) 输出为1,1,1,1,1 void List::insertInOrder( int data) { Node *n

我试图在链表中按升序插入一个新元素,我输入3,1,9,7,5的代码输出1,1,1,1,1,1,1,但是我想要的输出是1,3,5,7,9

head实际上位于类列表的私有实例变量中,这是一个成员函数

它被称为:

列表a
a.insertinoder(3);a、 插入诺德(1);a、 插入诺德(9);a、 插入诺德(7);插入诺德(5)

输出为1,1,1,1,1

          void List::insertInOrder( int data) {

              Node *newNode = new Node; 
               newNode->data=data;

              if(head == null || head->data > data) { 
                 newNode->next = head; 
                 head = newNode; 
              }
              else{ 
                 Node *cur = head; 

                 while(cur->next != null && current->next->data < data) 
                   cur = cur->next; 
                 newNode->next = cur->next;
                 cur->next = newNode;
              } 
         }
void List::insertinoder(int数据){
Node*newNode=新节点;
新建节点->数据=数据;
如果(head==null | | head->data>data){
新建节点->下一步=头部;
头=新节点;
}
否则{
节点*cur=头部;
while(cur->next!=null&¤t->next->datanext;
新建节点->下一步=当前->下一步;
cur->next=newNode;
} 
}

您没有递增
nextC
,因此您的while循环只将
数据
与一个数字进行比较
cur
不执行任何操作,因为您没有像使用
nextC
一样在条件中使用它

while(cur->next != null && nextC->data < data) //nextC->data is set only once
                   cur = cur->next; //cur incremented, but for what?
while(cur->next!=null&&nextC->datadata只设置一次
cur=cur->next//cur增加了,但是为了什么?

似乎基本有效,但:

while(cur->next!=null&¤t->next->data
在这里,您在一个条款中提到“cur”,在另一个条款中提到“current”。 “current”似乎不存在,但也许你有globals


但是,即使这样也会破坏排序,因此我怀疑错误出现在输出代码中,而不是排序代码中。

问题是什么?我看到两个问题:1.数据没有存储到列表中,因为它没有分配给newNode->data 2.如果您想要排序的链表,为什么总是将“data”与“nextC”勾选f'cur'?@VladimirM感谢您的关注,我将其更改为“当前->下一步->数据”,但输出仍然是一样的。我删除了NextInsertInoder函数。输出函数和添加项的函数也可以吗?虽然通常只将代码限制在相关部分是很好的,但如何调用InsertInor可能存在问题或者你如何打印,你能把代码也发布出来吗?请给我看一下你的输出代码。我复制了你的代码,添加了列表和节点最简单的类,并且做了:
List l;l.insertinoder(3);l.insertinoder(1);insertinoder(9);l.insertinoder(3);Node*h=l.head;while(h){cout data我更新了while循环,但是结果还是一样的
       while(cur->next != null && current->next->data < data)