[英]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.