链表
是解决变长数组的良好方式,可以自适应的增长空间长度,同时方便做定向插入和删除。
一、链表的结构
链表的各个储存单元称为结点。一个结点主要由两个部分组成,一是数据本身,另一部分是后继指针,用于指向后一个数据,以形成链表。
首先定义一个结构体变量来储存结点。
struct node {
int data;
struct node *next;
}
第二步,建立链表。
首先需要一个头指针head指向链表的最开端,当然首先第一个结点的head应该为NULL,也就是应该将head初始化为NULL,头指针在后续的遍历操作中起着重要作用。
struct node *head;
head=NULL;
接着需要创建第一个结点,同时使用一个临时指针指向该结点
struct node *p;
p=(struct node *)malloc(sizeof(struct node));
接下来构建这个结点的数据部分和后继部分
cin>>a;
p->data = a;
p->next =NULL; //当前暂无下一个结点,指向为空
最后我们使用头指针来遍历整个链表
if(head==NULL) head = p; //若为第一个结点,则用头指针指向该结点
else q->next = p; //否则的话则将上一个结点的后继指针指向当前结点
q=p; //将q与p同步,以便继续遍历下一个结点
整体代码:
#include <iostream>
#include <cstring>
#include <stdlib.h>
using namespace std;
//链表 linked-list
struct node {
int data;
struct node *next;
};
int main() {
struct node *head,*p,*q,*t;
int i,n,a;
cin>>n;
head=NULL;
for(int i=0;i<n;i++) {
cin>>a;
p=(struct node *)malloc(sizeof(struct node));
p->data=a;
p->next = NULL;
if(head==NULL) head = p;
else q->next = p;
q=p;
}
t=head;
while(t!=NULL) {
cout<<t->data;
t=t->next;
}
return 0;
}
//该代码没有释放内存空间,需注意
插入操作。
如果我们需要插入一个数据到刚好的位置上(符合大小关系)。
t=head; //创建临时指针遍历
cin>>a;
while(t!=NULL) { //一直循环到尾
if(t->next==NULL||t->next->data>a){ //在链表的最后或后一个数据大于a的时候插入
p=(struct node*)malloc(sizeof(struct node));
p->data=a;
p->next=t->next;
t->next=p;
break;
}
t=t->next;
}
完整代码:
#include <iostream>
#include <cstring>
#include <stdlib.h>
using namespace std;
//链表 linked-list
struct node {
int data;
struct node *next;
};
int main() {
struct node *head,*p,*q,*t;
int i,n,a;
cin>>n;
head=NULL;
for(int i=0;i<n;i++) {
cin>>a;
p=(struct node *)malloc(sizeof(struct node));
p->data=a;
p->next = NULL;
if(head==NULL) head = p;
else q->next = p;
q=p;
}
cin>>a;
t=head;
while(t!=NULL) { //一直循环到尾
if(t->next==NULL||t->next->data>a){ //在链表的最后或后一个数据大于a的时候插入
p=(struct node*)malloc(sizeof(struct node));
p->data=a;
p->next=t->next;
t->next=p;
break;
}
t=t->next;
}
t=head;
while(t!=NULL) {
cout<<t->data<<" ";
t=t->next;
}
return 0;
}