个人理解:
某种程度上可以说,链表就是结构体。所以学链表之前先去学结构体
这个结构体包含我们想记录的数据,还包含一个指针,指向下一个结构体,如此反复套娃,直到这个指针最终指向空,这一堆结构体便被称为链表。
一.创建链表
我们只需要把它的头搞出来就行。
首先是创建一个结构体
#include<bits/stdc++.h>
using namespace std;
typedef struct listnode{
int num;
struct listnode *next;
}mynode;
然后创个头
int main()
{
mynode *head;
mynode *list;
mynode *temp;
head=(mynode*)malloc(sizeof(mynode));
head->next=NULL;//创建头结点
list=(mynode*)malloc(sizeof(mynode));
list=head;//给咱的链表装个头上去
}
二.链表添加节点
for(int i=0;i<5;i++)
{
int x;
cin>>x;
temp=(mynode*)malloc(sizeof(mynode));
temp->num=x;
temp->next=NULL;
list->next=temp;
list=temp;
}
三.链表输出
temp=head->next;
if(temp->next==NULL)
cout<<endl;
else
{
while(temp!=NULL)
{
cout<<temp->num<<" ";
temp=temp->next;
}
cout<<endl;
}
完整代码
#include<bits/stdc++.h>
using namespace std;
typedef struct listnode{
int num;
struct listnode *next;
}mynode;
int main()
{
mynode *head;
mynode *list;
mynode *temp;
head=(mynode*)malloc(sizeof(mynode));
head->next=NULL;//创建头结点
list=(mynode*)malloc(sizeof(mynode));
list=head;//给咱的链表装个头上去
for(int i=0;i<5;i++)
{
int x;
cin>>x;
temp=(mynode*)malloc(sizeof(mynode));
temp->num=x;
temp->next=NULL;
list->next=temp;
list=temp;
}
temp=head->next;
if(temp->next==NULL)
cout<<endl;
else
{
while(temp!=NULL)
{
cout<<temp->num<<" ";
temp=temp->next;
}
cout<<endl;
}
}
四.删除节点
让指向要删除节点的指针指向要删除节点的下一个节点
例题:
锯齿矩阵是指每一行包含的元素个数不相同的矩阵,比如:
1
3 5 2 6 1
2
2 3 4
3
1 6 2 7
初始时矩阵为空,读入 mm 对整数 (x,y)(x,y),表示在第 xx 行的末尾加上一个元素 yy。
输出最终的锯齿矩阵。
输入格式
第一行输入两个整数 n,m\ (1 \leq n,m \leq 10000)n,m (1≤n,m≤10000),其中 nn 表示锯齿数组的行数,mm 表示插入的元素总数。
接下来一共 mm 行,每行两个整数 x,y\ (1 \leq x \leq n, 0 \leq y \leq 10000)x,y (1≤x≤n,0≤y≤10000),表示在第 xx 行的末尾插入一个元素 yy。
输出格式
一共输出 nn 行,每行若干个用空格分隔的整数。如果某行没有任何元素,则输出一个空行。
输出时每行末尾的多余空格,不影响答案正确性
样例输入复制
3 12 1 3 2 2 2 3 2 4 3 1 3 6 1 5 1 2 1 6 3 2 3 7 1 1
样例输出复制
3 5 2 6 1 2 3 4 1 6 2 7
#include<bits/stdc++.h>
using namespace std;
typedef struct ANode{
int num;
struct ANode *next;
}ArcNode;
int main()
{
int n,m;
cin>>n>>m;
ArcNode *head[n];
ArcNode *list[n];
ArcNode *temp;
for(int i=0;i<n;i++)
{
head[i]=(ArcNode*)malloc(sizeof(ArcNode));
head[i]->next=NULL;//创建头结点
list[i]=(ArcNode*)malloc(sizeof(ArcNode));
list[i]=head[i];//给咱的链表装个头上去
}
for(int i=0;i<m;i++)
{
int x,y;
cin>>x>>y;
temp=(ArcNode*)malloc(sizeof(ArcNode));
temp->num=y;
temp->next=NULL;
list[x-1]->next=temp;
list[x-1]=temp;
}
for(int i=0;i<n;i++)
{
temp=head[i]->next;
if(temp->next==NULL)
cout<<endl;
else
{
while(temp!=NULL)
{
cout<<temp->num<<" ";
temp=temp->next;
}
cout<<endl;
}
}
}