今天浅谈一下链表,(感谢zz大佬的帮助!!!orz)
怎么说呢?链表我觉得挺像链式向前星存图捏
众所周知,链表相对于数组的优越性在于,它可以实现灵活的内存动态管理,并且节点的数量可以扩充,删除插入一个元素容易。接下来进入今天的正题。
实现链表的增删改查!!!

如图所示,所谓链表,就是由若干个节点组成,而每个节点就是由数据域和指针域组成。每个指针域指向下一个的首元节点
接下来,我来介绍两种方法来构造链表并且遍历整个链表。
I:构造链表并且遍历
1:构造函数法
#include<iostream>
using namespace std;
struct Node{
Node(const int&d):data(d),next(0){}//构造函数
int data;//数据域
Node *next;//指针域
};
int main( ){
int n,d;
Node *first,*last;
cin>>n;//输入n个数字
n--;
cin>>d;
last=first=new Node(d);
while(n--){
cin>>d;
Node *P=new Node(d);
last->next=P;
last=P;
}
for(Node *p=first;p;p=p->next){
cout<<p->data<<" ";
}//遍历一遍链表
}
2:不需要构造函数(我是真的想不出叫什么方法了TAT)
#include<iostream>
using namespace std;
struct Node{
int data;//数据域
Node *next;//指针域
};
int main( ){
int n,d;
Node *first,*last;
cin>>n;//输入n个数字
n--;
cin>>d;
last=first=new Node;
last->data=first->data=d;
last->next=first->next=0;
while(n--){
cin>>d;
Node *P=new Node;
P->data=d;
P->next=0;
last->next=P;
last=P;
}
for(Node *p=first;p;p=p->next){
cout<<p->data<<" ";
}//遍历一遍链表
}
II:删除一个节点(接下来的操作,我基本选择不构造函数的方法)

如图所示,就是把p0的连接到p的下一个节点。
#include<iostream>
using namespace std;
struct Node{
int data;//数据域
Node *next;//指针域
};
int main( ){
int n,d;
Node *first,*last;
cin>>n;//输入n个数字
n--;
cin>>d;
last=first=new Node;
last->data=first->data=d;
last->next=first->next=0;
while(n--){
cin>>d;
Node *P=new Node;
P->data=d;
P->next=0;
last->next=P;
last=P;
}
Node *pos1,*pos2;
//假如我要删除3,输入1 2 3 4 5
for(Node *p=first;p;p=p->next){
if(p->data==2){
pos1=p;
pos2=p->next;
break;
}
}
pos1->next=pos2->next;
delete pos2;
for(Node *p=first;p;p=p->next){
cout<<p->data<<" ";
}//遍历一遍链表
}
III 增加一个数字

#include<iostream>
using namespace std;
struct Node{
int data;//数据域
Node *next;//指针域
};
int main( ){
int n,d;
Node *first,*last;
cin>>n;//输入n个数字
n--;
cin>>d;
last=first=new Node;
last->data=first->data=d;
last->next=first->next=0;
while(n--){
cin>>d;
Node *P=new Node;
P->data=d;
P->next=0;
last->next=P;
last=P;
}
Node *pos=new Node;
pos->data=6;
pos->next=0;
//我在3和4之间加入一个6,输入1 2 3 4 5
for(Node *p=first;p;p=p->next){
if(p->data==3){
pos->next=p->next;
p->next=pos;
break;
}
}
for(Node *p=first;p;p=p->next){
cout<<p->data<<" ";
}//遍历一遍链表
}
本文详细介绍了链表的构造方法,包括使用构造函数和不使用构造函数两种方式,并演示了如何进行增删改查操作。通过实例展示了删除节点、插入数字的过程,适合理解链表基本概念和技术应用。
944

被折叠的 条评论
为什么被折叠?



