簡體   English   中英

需要代碼說明

[英]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;
}
}

在insert_beg中,將開始的指針更改為新的開始位置,該位置是新插入的節點。

我認為,指針操作最好在圖形模型中理解。

指針問題以圖形方式說明

為什么在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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM