[英]Need explanation for the code
为什么在main()中显示的参数开始而不是newptr? 另外,np-> next = save如何; 和np = np->下一步在各自的功能? 我对链接列表的概念很陌生。 任何帮助将非常感激。
#include<iostream>
using namespace::std;
struct node
{
int info;
node *next;
} *start,*newptr,*save,*ptr;
node * create_new_Node(int);
void insert_beg(node *);
void display(node*);
int main()
{
start=NULL;
int inf; char ch='y';
while(ch=='y'||ch=='Y')
{
system("cls");
cout<<"Enter information for the new node : \n";
cin>>inf;
cout<<"\nCreating new node";
system("pause");
newptr=create_new_Node(inf);
if(newptr!=NULL)
{
cout<<"New node created successfully.";
system("pause");
}
else
{
cout<<"\aNot enough memory =S ...\n";
exit(1);
}
cout<<"Now inserting this node to the beginning of the list :";
system("pause");
insert_beg(newptr);
cout<<"Now the list is : ";
display(start);
cout<<"Press Y or y to enter more nodes :::: ";
cin>>ch;
}
return 0;
}
node * create_new_Node(int n)
{
ptr=new node;
ptr->info=n;
ptr->next=NULL;
return ptr;
}
void insert_beg(node *np)
{
if(start==NULL)
{
start=np;
}
else
{
save=start;
start=np;
np->next=save;
}
}
void display(node * np)
{
while(np!=NULL)
{
cout<<np->info<<" -> ";
np=np->next;
}
}
为什么在main()中显示的参数开始而不是newptr?
因为start
是链表中的头指针,并且始终指向链表中的第一个节点。 要显示链接列表,您必须从第一个节点开始,并且第一个节点由start
指针指向。
np-> next = save如何; 和np = np->下一步在各自的功能?
np->next=save;
这意味着节点np
next
指针应指向save
指针所指向的节点。
np=np->next;
它在display
功能中用于迭代链接列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.