2015-11-06 144 views
-2

看起来像在“SortedInsert”中,头部始终为零,然后代码段错误...无论如何...真的令人沮丧。任何想法为什么头总是零,即使我把它设置为某些东西,然后为什么代码段错误一般? 感谢插入已排序的链接列表段落默认

#include <iostream> 
#include <cassert> 
#include <string> 
#include <stdlib.h> 
#include <sstream> 
using namespace std; 

struct Node { 
    Node* next = 0; 
    int data; 
    ~Node(){ 
     if (next != 0){ 
      delete next; 
     } 
    } 
}; 

void SortedInsert(Node* head, int value){ 
    if(head == 0){ 
     Node* header = new Node; 
     header->data = value; 
     head = header; 
     return; 
    } 
    cout << "TEST" << endl; 
    Node* temp = head; 
    while(temp != 0){ 
     if(value > temp->data){ 
      Node* insert = temp->next; 
      Node* otherTemp = new Node; 
      otherTemp->data = value; 
      temp->next= otherTemp; 
      temp->next->next = insert; 
     } 
    temp=temp->next; 
    } 
    return; 
    } 

int main() { 
    srand(32); 
    Node* sortedList = 0; 
    for (int i = 0; i < 10; i++){ 
     SortedInsert(sortedList, rand() % 100); 
    } 

    Node* temp = sortedList; 
    for (int i=0; i < 9; i++){ 
     assert(temp->data <= temp->next->data); 
     temp = temp->next; 
    } 

    delete sortedList; 
} 
+2

您可能会取消引用未初始化的指针。通过您的调试器来找出错误的来源。 –

回答

0

SortedInsert都有自己的头指针的副本。当你在函数内改变头部时,它不会影响main中的值。解决方案是通过引用或通过地址传递头部。

void SortedInsert(Node** head, int value) { 
    //Use *head to refer to the head of the list 
} 
int main() { 
    ... 
    Node* sortedList = 0; 
    SortedInsert(&sortedList, ...); 
    ... 
} 

或者

void SortedInsert(Node*& head, int value) { 
    //Use head to refer to the head of the list 
} 
int main() { 
    ... 
    Node* sortedList = 0; 
    SortedInsert(sortedList, ...); 
    ... 
} 
0

请尝试以下

void SortedInsert(Node* &head, int value) 
{ 
    if (head == nullptr || value < head->data) 
    { 
     head = new Node { head, value }; 
    } 
    else 
    { 
     Node *current = head; 

     while (current->next != nullptr && !(value < current->next->data)) 
     { 
      current = current->next; 
     } 

     Node *tmp = new Node { current->next, value }; 
     current->next = tmp; 
    } 
} 

至于你funcion实现,那么该函数涉及的头的副本。副本的任何更改都不会影响参数本身。你应该通过引用传递头部或者从函数返回头部。