不能保持链表的头部不变

can not keep the head of a linked list unchanged

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

#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 ;
}

对于 create_linkedlist() 函数中的第二个元素(循环的第一次迭代),tmhead 为 NULL 并且您正在尝试 de-reference 它会导致崩溃。

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

也尝试使用特定的 header 而不是 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,则您的代码会出现错误。最好在循环中包含 header 节点创建和填充。

经过上述所有更改后,函数可能如下所示 -

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 ;
}