【发布时间】: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