2014-09-23 42 views
0

我刷了我的C++编程技能的采访,我想了解在这个代码我写了一个链表有些事情正在发生可怕的错误与我的链表代码

struct Node 
{ 
    int data; 
    Node *next; 
} *Head ; 

void ListInit() 
{ 
    Head = NULL; 
} 

void addfront(Node *Head, int data) 
{ 
    Node *newnode = new Node; 
    newnode->data = data; 
    newnode->next = Head; 
    Head = newnode; 
} 

void displaylist(Node *Head) 
{ 
    Node *cur; 
    cur = Head; 
    if(cur==NULL) 
    { 
     cout<<"List is Empty ! "; 
    } 

    while(cur->next!=NULL) 
    { 
     cout<<" "<<cur->data<<" "; 
     cur = cur->next; 
    } 
} 

int main() 
{ 
    ListInit(); 
    addfront(Head,5); 
    addfront(Head,6); 
    addfront(Head,8); 
    addfront(Head,1); 
    addfront(Head,9); 

    displaylist(Head); 
    return 0; 
} 

错误当我运行这个代码块时,代码块崩溃,所以我猜测它是一个段错误。但我无法弄清楚为什么它潜入此。

+4

除了新的代替malloc和COUT代替了printf,这是C. – 2014-09-23 13:42:34

+2

在'addfront'你只修改'Head'的本地副本。 – 2014-09-23 13:43:14

+1

@NeilKirk:那么?这意味着它仍然是C++。 – Deduplicator 2014-09-23 13:45:23

回答

3

Itjax已经回答了你的问题,但除了那个改变,这Itjax建议你也需要改变这一点:

if(cur==NULL) 
{ 
    cout<<"List is Empty ! "; 
} 

为:

if(cur==NULL) 
{ 
    cout<<"List is Empty ! "; 
    return; 
} 

否则,当您的列表为空时,您的代码将再次崩溃。

2

问题是,您只是在addFront中修改头指针的副本。尝试通过使其成为一个参考值改变原:

void addfront(Node*& Head, int data) // note the extra & 
{ 
    Node *newnode = new Node; 
    newnode->data = data; 
    newnode->next = Head; 
    Head = newnode; 
} 
1

ltjax是对的。在函数addfront()中,您可以更改局部变量Head的值,它与全局名称相同。不要那样做!这是一种非常糟糕的风格。 此外,应用程序不会掉落,然后函数displaylist()作为别的东西作出反应而不是显示消息。消息结束后使用回:

if (cur == NULL) 
{ 
    cout << "List is Empty!"; 
    return; 
} 

或沿着分支否则继续循环:

if (cur == NULL) 
{ 
    cout << "List is Empty!"; 
} 
else 
{ 
    while (cur-> next! = NULL) 
    { 
     cout << "" << cur-> data << ""; 
     cur = cur-> next; 
    } 
}