当前位置: 代码迷 >> 综合 >> c++中链表的实现,使用new动态内存
  详细解决方案

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

热度:7   发布时间:2023-10-15 13:18:54.0

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

#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赋下一个节点地址,再加数据即可。