【问题标题】:can not keep the head of a linked list unchanged不能保持链表头部不变
【发布时间】:2019-11-23 03:02:27
【问题描述】:

我是链表的新手。最近我试图创建一个程序,它以数组及其大小作为输入。然后它将数组转换为链表并打印元素。但是程序不工作,我猜这是因为头指针被改变了。那么,我能做些什么来保持头节点不变呢?

#include<bits/stdc++.h>
using namespace std ;
struct node
{
    int data ;
    node* link ;
};

node* create_linkedlist (int ara[] , int siz )
{
    node* head = NULL ;
    node* temp = new node() ;
    temp->data = ara[0] ;
    temp->link = NULL ;
    head = temp ;
    node* tmhead = head->link ;
    node* temp2 ;
    for(int i = 1 ; i < siz ; i++)
    {
        temp2 = new node() ;
        temp2->data = ara[i] ;
        temp2->link = NULL ;

        while ( tmhead->link!= NULL)
        {
            tmhead = tmhead->link ;
        }

        tmhead->link = temp2 ;
    }

    return head ;
}

void printlist( node* h_ref )
{
    while (h_ref != NULL)
    {
        printf("%d " , h_ref->data) ;
         h_ref = h_ref->link ;
    }
}


int main()
{
    int siz ;
    cin>> siz ;
    int ara[siz + 2];
    for(int i = 0  ; i < siz ; i++)
    {
        cin >> ara[i] ;
    }
    node* hd = create_linkedlist(ara , siz) ;
    node* temp = hd ;
    printlist(temp) ;
    return 0 ;
}

【问题讨论】:

    标签: c++ data-structures singly-linked-list


    【解决方案1】:

    对于create_linkedlist() 函数中的第二个元素(循环的第一次迭代),tmhead 为 NULL,而您试图取消引用它会导致崩溃。

    node* tmhead = head-&gt;link ; 行更改为node* tmhead = head;,它应该可以正常工作。

    同时尝试使用特定的标头而不是 bits/stdc++.h 并使用 nullptr 而不是 NULL。您也不需要 for 循环内的 while 循环。摆脱它,只需像下面那样更改 for 循环 -

    for(int i = 1 ; i < siz ; i++)
    {
        temp2 = new node() ;
        temp2->data = ara[i] ;
        temp2->link = NULL ;
    
        tmhead->link = temp2 ;
        tmhead = tmhead->link ;
    }
    

    请注意,如果用户提供的大小为 0,您的代码将出现错误。最好包括头节点的创建,循环内的填充。

    通过所有提到的更改,函数可能看起来像这样 -

    node* create_linkedlist (int ara[] , int siz )
    {
        node* head = nullptr;
        node* temp = nullptr;
        node* last = nullptr; // Keeps track of last inserted node
        for(int i = 0; i < siz; i++)
        {
            temp = new node();
            temp->data = ara[i];
            temp->link = nullptr;
    
            if (!head) {
              head = temp;
            }
    
            if (last) {
              last->link = temp;
            }
            last = temp;
        }
        return head ;
    }
    

    【讨论】:

    • if (last) { last->link = temp; } last = temp 你是什么意思?为什么我必须使用特定的头文件名而不是 bits/stdc++.h?
    • @MD.MarufHasam, if (last) 检查last 是否持有有效指针而不是nullptr。如果它是有效的,那么我们将取消引用它并将新创建的节点添加到列表的末尾。所以,在第一次迭代中,这个if 块将不会被执行。但是为了跟踪最后插入的节点,我们将始终将last 分配给新创建的节点(即使在第一次迭代中也是如此)。第二个问题请参考-stackoverflow.com/questions/31816095/…
    猜你喜欢
    • 2014-04-09
    • 2012-07-13
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多