私はC++でデータ構造を学習しています。これは、リンクとノードを使用した の簡単な挿入プログラムです。挿入はノードの先頭で行われます。 コードの一部がわかりません。C++でのデータ構造。リンクリストのノードの先頭に挿入
display()
のポインタnp
は、挿入された情報をポイントし、次のノードを使用して以前の情報の値をとります。次のポインタは、insert_beginning()
関数を使用して前の情報を指しています。 表示はwhile
ループを使用して行われます。次のポインタは各ループの間にどのように値を変更しますか?
PS:プログラムはうまく動作します。
#include<iostream>
#include<process.h>
#include<cstdlib>
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*);
/*----------------------------------------------------------------------------------------------------------------------------
The pointer 'start' points to the beginning of the list.
Function 'create_new_node()' takes one integer argument , allocates memory to create new node and returns
the pointer to the new node.(return type: node*)
Function 'insert_beg()' takes node* type pointer as an argument and inserts this node in the beginning of the list.
Function display takes node* type pointer as an argument and displays the list from this pointer till the end of the list
------------------------------------------------------------------------------------------------------------------------------
*/
int main()
{
start=NULL;
int inf;
char ch='y';
while(ch=='y'||ch=='Y')
{
system("cls");
cout<<"enter information for the new node ";
cin>>inf;
cout<<"\ncreating new node. Press enter to continue ";
system("pause");
newptr = create_new_node(inf);
if(newptr!=NULL)
{
cout<<"\nnew node created successfully. Press enter to
continue. ";
system("pause");
}
else
{
cout<<"\nCannot create new node. ABORTING!! ";
exit(1);
}
cout<<"\nnow inserting this node in the beginning of the list.
Press enter to continue ";
system("pause");
insert_beg(newptr);
cout<<"\nNow the list is \n";
display(start);
cout<<"\nPress 'Y' to enter more nodes, 'N' to exit\n";
cin>>ch;
}
return 0;
}
node *create_new_node(int n)
{
ptr=new node;
ptr->info=n;
ptr->next=NULL;
}
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;
}
cout<<"!!!\n";
}
ノードを挿入すると、関数表示はどのように関連していますか? –
リンクリストのすべてのノードには次のノードのアドレスが含まれているので、 'np-> next'は' np'np-> next'に 'np'に割り当てられている次のノードを指します。次のノードに移動します。 –