C++中简单链表的制作
我试图学习链表,这个函数makeList应该使用字符串列表中的输入创建并返回链表。老实说,我有点迷路了。任何帮助都将不胜感激 首先,返回链接列表的最后一个节点。。我认为您应该返回头部并将其分配给第一个节点 其次,您正在使用cin.fail作为字符串,我认为不应该这样做。如果存在数据不匹配,cin.fail将起作用,对于string,我认为这很少见 该函数看起来有点像:C++中简单链表的制作,c++,string,linked-list,cin,C++,String,Linked List,Cin,我试图学习链表,这个函数makeList应该使用字符串列表中的输入创建并返回链表。老实说,我有点迷路了。任何帮助都将不胜感激 首先,返回链接列表的最后一个节点。。我认为您应该返回头部并将其分配给第一个节点 其次,您正在使用cin.fail作为字符串,我认为不应该这样做。如果存在数据不匹配,cin.fail将起作用,对于string,我认为这很少见 该函数看起来有点像: struct Node{ string val; Node* next; }; Node* makeList
struct Node{
string val;
Node* next;
};
Node* makeList ()
{
string current;
Node* n;
Node* head= NULL;
Node* temp = n;
while(cin>>current && !cin.fail())
{
n = new Node;
n->val = current;
temp ->next = n;
temp = temp -> next;
}
n->next = NULL;
return n;
}
首先,由于你的临时参数代表了最后一个元素,我在开始时把它放在NULLPTR中,这更多的是C++的精神,所以我会在文本中使用它。
之后,在while循环中,当您添加新元素时,您应该写入n->next=nullptr,因为新元素的next指针如果您总是将其添加到列表的后面,那么它将始终指向nullptr。在您的实现中,新元素n总是指向自身。稍后在while循环中,您需要检查head==nullptr,如果这是真的,那么您应该将head分配给使head=n的新元素。如果head不等于nullptr,则需要将元素n添加到back temp->next=n。在循环的and处,您应该将n元素指定为last temp=n,该元素必须位于else块之外,因为它在上述两种情况下都是这样做的。我恐怕最重要的答案都有一些错误
Node* makeList ()
{
string current;
Node* n;
Node* head= NULL;
Node* temp = n;
while(cin>>current && !cin.fail())
{
if(current == "0")
break;
n = new Node;
n->val = current;
temp ->next = n;
temp = temp -> next;
if(!head)
head = n;
}
n->next = NULL;
return head;
}
Node *make_link_list_from_input(){
string value;
Node *head = nullptr;
Node *current = nullptr;
Node *last = nullptr;
while (cin >> value){
current = new Node();
if(head== nullptr){
head = current;
}
if(last!= nullptr){
last->next=current;
}
last=current;
}
if(last != nullptr) {
last->next = nullptr;
}
return head;
}