我运行我的程序,当它运行完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()的最后一次调用会给你空pch,你试图将它作为最后一个元素添加到链表中。这是一个简单的修复将使您的代码运行:
while (pch != NULL)
{
pch = strtok(NULL, " ");
if(pch!=NULL) // do not add empty data to your linked list
{
addNode(head, pch);
}
}