显示链接列表c ++后停止

时间:2016-01-07 03:46:31

标签: c++ linked-list

我运行我的程序,当它运行完成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";
}

1 个答案:

答案 0 :(得分:3)

正如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);
    }
}