2016-04-07 60 views
1

下面的朴素代码实现了一个链表,不打印主函数中的所有元素,一切都会好的。然而,LinkedList::printll函数将触发一个设置错误(海湾合作委员会5.3.0),这个问题涉及到适当的处理头节点我想...链表中的头节点

那么,有没有什么办法让这段代码的工作printll函数的最小修改?

#include <iostream> 

using namespace std; 

struct Node{ 
    int value; 
    Node* next; 
}; 

struct LinkedList{ 
    Node* head= NULL ; 
    void append(int); 
    void printll(); 
}; 

void LinkedList::append(int data){ 
    Node* cur = head; 
    Node* tmp = new Node; 
    tmp->value = data; 
    tmp->next = NULL; 

    if(!cur){ 
     cur = tmp;      // cur-> head 
    } 
    else{ 
     while(cur->next != NULL){ 
     cur = cur->next; 
     } 
     cur->next = tmp; 
    } 
    std::cout<<cur->value<<std::endl; // cur-> temp 
    delete tmp;       // comment out 
} 

void LinkedList::printll(){ 
    Node* cur = head; 
     while(cur->next != NULL){  // 
     std::cout<<cur->value<<std::endl; 
     cur = cur->next; 
     } 
} 


int main(){ 
    LinkedList LL; 
    LL.append(5); 
    LL.append(6); 
    LL.append(7); 
    LL.printll(); // --without this, the program is fine 
    return 0; 
} 

回答

3

你有一些错误的append

if(!cur){ 
    cur = tmp; 
} 

这仅分配给本地副本。我假设你在这里尝试设置head,那么请这样做:head = tmp;。请注意,在这种情况下,您无法打印cur,因为您尚未设置。但你可以打印tmp->value

然后:

delete tmp; 

你只刚刚创建,并将其分配到的地方 - 你为什么要删除它?你知道还有一个指向它的指针。只有当您完成清理清单时(此时您根本没有这样做),它才会被清除。

除此之外,您printll不会打印的最后一个元素 - 想想什么时候会停止:

A -> B -> C -> NULL 

它将停止节点C,但从来没有打印C的价值。只需更换:

while(cur->next != NULL){ 

while(cur != nullptr){ 

(还有,我不喜欢endl)。

See here for these changes running

#include <iostream> 

struct Node{ 
    int value; 
    Node* next; 
}; 

struct LinkedList{ 
    Node* head = nullptr ; 
    void append(int); 
    void printll(); 
}; 

void LinkedList::append(int data){ 
    Node* cur = head; 
    Node* tmp = new Node; 
    tmp->value = data; 
    tmp->next = nullptr; 

    if(!cur){ 
     head = tmp; 
    } 
    else{ 
     while(cur->next != nullptr){ 
      cur = cur->next; 
     } 
     cur->next = tmp; 
    } 
} 

void LinkedList::printll(){ 
    Node* cur = head; 
    while(cur != nullptr){ 
     std::cout << cur->value << '\n'; 
     cur = cur->next; 
    } 
} 


int main(){ 
    LinkedList LL; 
    LL.append(5); 
    LL.append(6); 
    LL.append(7); 
    LL.printll(); 
} 
+0

作为@BoBTFish说,你必须删除'删除TMP;'从你的代码(为什么你'delete'一个'node'刚才添加它到'List'?),并在'printll'中改变'while'循环,建议:'while(cur)' –

+0

我改变了@BoBTFish所提出的所有建议,而且我正在使用GCC 5.3.0进行编译。 ,它仍然segfault ..问题发生在“cur-> next”我猜 – lorniper

+0

@lorniper当我做了我建议的更改,我能够编译和正常运行。你可以发布你的确切代码仍然是残疾人吗? – BoBTFish

0

1.you水湿

delete tmp; 

原因TMP是一个指针,当您运行删除tmp目录,您删除的对象。

2.打印功能应该是这样的:

void LinkedList::printll(){ 
    Node* cur = head; 
     while(cur->next != NULL){  // -> problems is here 
     std::cout<<cur->value<<std::endl; 
     cur = cur->next; 
     } 
     std::cout<<cur->value<<std::endl; 
}