c++中链表的实现,使用new动态内存

利用动态内存, 我们也可以做出链表, 可以不断增长的数组:

#include <iostream>
#include <cstdio>

using namespace std;

struct node
{    
    //链表的节点
    int data;//数据
    int num;//节点编号
    struct node *next;//指向下一个节点
};

int main()
{
    struct node *head/*头节点*/, *p, *q;
    head=NULL;
    p=NULL;
    q=new node;
    q->next=NULL;
    q->num=1;
    int a=-1;
    cout<<"请输入第1个数字:";
    cin>>a;
    q->data=a;
    head=q;
    while (a!=0)
    {
        p=q;
        q=new node;
        q->next=NULL;
        p->next=q;
        q->num=p->num+1;
        cout<<"请输入第"<<q->num<<"个数字:";
        cin>>a;
        q->data=a;
    }

    //前面都是输入,这以下都是输出

    q=head;
    p=NULL;
    while (q->data!=0)
    {
        printf("%d %d\n",q->num,q->data);
        q=q->next;
    }
    
    //释放内存

    q=head;
    p=q;
    while(q->next!=NULL)
    {
        p=q->next;
        delete []q;
        q = p;  
    }
    return 0;
}

->: 用指针访问结构体内的变量。

在链表中插入、删除节点也很简单, 先给next赋下一个节点地址,再加数据即可。

猜你喜欢

转载自blog.csdn.net/qq_34729246/article/details/106446550