【发布时间】:2021-05-30 20:15:22
【问题描述】:
我想接受一长串数字并插入到双向链表中,每个节点有 4 个字符(数字)。 下面是我的代码。它将输入作为数字,但显示“程序以现有代码 0 完成” 请帮助我在这里错过了什么?
#include <iostream>
#include <string>
#include <conio.h>
using namespace std;
struct Node {
string data;
struct Node* prev;
struct Node* next;
};
struct Node* head = NULL;
void insert(string newdata) {
struct Node* newnode = (struct Node*)malloc(sizeof(struct Node));
newnode->data = newdata;
newnode->prev = NULL;
newnode->next = head;
if (head != NULL)
head->prev = newnode;
head = newnode;
cout << "\nNode inserted";
}
void display() {
struct Node* ptr;
ptr = head;
while (ptr != NULL) {
cout << ptr->data << " ";
ptr = ptr->next;
}
}
int main() {
string n1, temp;
cout << "Enter the number\n";
cin >> n1;
int len, i;
len = n1.size();
cout << "\n Length is " << len;
getch();
// temp= n1;
// cout<<"\n line is "<<temp.substr(len);
for (i = 0; i < len; i = i + 4) {
// temp = n1.substr(i,4);
insert(n1.substr(i, 4));
}
cout << "\nThe doubly linked list is: ";
display();
return 0;
}
【问题讨论】:
-
您不能将
malloc与Node一起使用,因为Node 的构造函数不会运行并且您将访问一个未初始化的字符串对象。使用newnode = new Node;(并为 Node 提供一个适当的构造函数,这样您就不必分配给每个字段)。 -
另一种方法是使用placement new 就地显式构造
string对象。但是,这不是好的 C++ 编程风格。但它会更符合 OP 的 C 风格的解决方案。
标签: c++ string doubly-linked-list