gpt4 book ai didi

c++ - 显示链表c++后停止

转载 作者:行者123 更新时间:2023-11-28 00:07:33 25 4
gpt4 key购买 nike

我运行我的程序,当它运行完成时 display(head) ,它将停止并且不会执行最后一行 cout << "Done";

谁能帮我解决这个问题:D

这是我的代码:

#include <iostream>
#include <cstring>
#include <stdlib.h>

using namespace std;

struct Node{
Node* next;
char* data;
};

void initNode(struct Node *head, char *n){
head->data = n;
head->next = NULL;
}

void addNode(struct Node *head, char *n){
Node *newNode = new Node;
newNode->data = n;
newNode->next = NULL;

Node *cur = head;
while(cur){
if(cur->next == NULL){
cur->next = newNode;
return;
}
cur = cur->next;
}
}

void display(struct Node *head){
Node *list = head;
while(list != NULL){
cout << list->data <<endl;
list = list->next;
}
}

int main(){
struct Node *head = new Node;
char str[] = "- This is a sample string";
char * pch;

pch = strtok (str," ");
initNode(head, pch);
while (pch != NULL){
pch = strtok(NULL, " ");
addNode(head, pch);
}

display(head);
cout << "Done";
}

最佳答案

正如 TonyD 指出的那样,对 strtok() 的最后一次调用为您提供了 NULL pch,您尝试将其作为最后一个元素添加到您的链表中。这是使您的代码运行的简单修复:

while (pch != NULL)
{
pch = strtok(NULL, " ");
if(pch!=NULL) // do not add empty data to your linked list
{
addNode(head, pch);
}
}

关于c++ - 显示链表c++后停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34647033/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com