请查看下面的代码片段。我正在尝试使用双指针概念将元素插入链表。
问题是:每次'Head'元素被分配给'NULL',这是不可取的,除了第一次插入。请给出解决这个问题的建议。
class Node{
public:
int item;
Node *next;
Node(){};
};
class List{
public:
Node *head;
Node **lpp1;
Node *lp1;
Node *newnode;
List(){head=NULL;};
void insert_node(Node*,Node**,Node*);
void delete_node(int,Node*,Node*);
.
.
.
.
.
};
void List::insert_node(Node* newlp,Node **lpp,Node *lp)
{
*lpp=head;
cout<<"n value of the *lpp points to :"<<*lpp;
cout<<"n Initial Address of the head is:"<<head;`
if((*lpp)!=NULL)
{
for(lpp=&head;(*lpp)!=NULL;lpp=&(*lpp)->next){
lp=*lpp;
if(newlp->item<lp->item){
newlp->next=lp;
*lpp=newlp;
break;
}
else{
lp->next=newlp;
*lpp=lp;
break;
}
}
}
else{
head=newnode;
cout<<"n address of head is :"<<head;
cout<<"n "<<head->item<<" is head.";
}
}
int main()
{
List l;
l.insert_node(l.newnode,l.lpp1,l.lp1);
}
我得到的输出是:
1st insertion:
Enter the element to be inserted:34
value of the *lpp points to : 0
Initial Address of the head is: 0
address of the head is :0x8dd2008
34 is head.
2nd Insertion:
Enter the element to be inserted:56
value of the *lpp points to : 0
Initial Address of the head is: 0
address of the head is :0x8dd2018
56 is head.
赋值"*lpp=head;"是不正确的,因为"lpp"是null,而"*lpp"试图解引用一个null(或未初始化)的指针。确保无论何时对指针解引用,该指针都不为空。
节点* * lpp1;节点* lp1;节点* newnode;成员没有初始化。你甚至不需要这些成员。在类List中所需要的只是指向头节点的指针。