链表,可以将之理解为一种结构体指针数据类型。c++的实现方式和c相比没有什么太大的区别。
首先定义一个结构体,
struct node
{
int data;
node *next;
};
typedef node* List;
这里data用于储存数据,node *next用于指向下一节点的地址。
由于我们平常使用的都是结构体的指针,这里就自定义一个数据类型List,用于表示链表。
创建一个链表
//创建一个单链表
void creat_List(List a,int length)
{
List b,c;
b=c=a;
int i=0,j;
while(i<length)
{
b=new node;
cin>>j;
b->data=j;
c->next=b;
c=b;
++i;
}
c->next=nullptr;
return ;
}
这里的nullptr和c语言的NULL其实差不多,但是由于一些原先,使用NULL可能会造成一些异常,这里建议使用nullptr,具体原因可以自行百度。
和c语言的申请空间差不多,这里使用了new来代替。注意,第一个创建的节点的下一节点应该指向的是nullptr。
插入节点
//从后插入节点
void push_back(List a,int num)
{
while(a->next)
a=a->next;
List b;
b=new node;
b->data=num;
b->next=nullptr;
a->next=b;
return ;
}
从表头依次遍历到表尾,再申请一块空间开储存数据
先将表尾指向新建的b,再让b指向nullptr。这样就成功插入节点。
删除节点
首先判断链表是否为空,然后依次遍历到对应的节点,先新建一个节点b,
让它指向待删除节点a的下一节点,再让节点a前一节点指向节点b后一节点(防止链表断开),最后再将节点b清空内存,删除成功。删除整个链表也是一样的操作。
//删除对应节点
void de_List(List a,int n)
{
int i=1;
if(Is_empty(a))
return ;
while(i!=n)
{
a=a->next;
++i;
}
List b;
b=a->next;
a->next=b->next;
delete b;
return ;
}
源码:
#include<bits/stdc++.h>
using namespace std;
struct node
{
int data;
node *next;
};
typedef node* List;
//创建一个单链表
void creat_List(List a,int length)
{
List b,c;
b=c=a;
int i=0,j;
while(i<length)
{
b=new node;
cin>>j;
b->data=j;
c->next=b;
c=b;
++i;
}
c->next=nullptr;
return ;
}
bool Is_empty(List a)
{
if(a->next)
return 0;
else
return 1;
}
//删除对应节点
void de_List(List a,int n)
{
int i=1;
if(Is_empty(a))
return ;
while(i!=n)
{
a=a->next;
++i;
}
a->next=a->next->next;
return ;
}
//删除整个链表
void de_all(List a)
{
List b;
while(a->next)
{
b=a->next;
a->next=b->next;
delete b;
}
cout<<"deleted!"<<endl;
return ;
}
//依次输出整个链表
void get_List(List a)
{
if(Is_empty(a))
{
cout<<"list is empty";
return ;
}
a=a->next;
while(a->next)
{
cout<<a->data<<" ";
a=a->next;
}
cout<<a->data;
cout<<endl;
return ;
}
//输出链表长度
int get_length(List a)
{
int i=0;
while(a->next)
{
a=a->next;
++i;
}
return i;
}
//查询对应节点的数据
int get_num(List a,int n)
{
if(Is_empty(a))
{
cout<<"list is empty";
return 0;
}
int i=0;
while(i!=n)
{
a=a->next;
++i;
}
return a->data;
}
//从头部插入节点
void push_front(List a,int num)
{
List b=new node;
b->next=a->next;
b->data=num;
a->next=b;
return ;
}
//从后插入节点
void push_back(List a,int num)
{
while(a->next)
a=a->next;
List b;
b=new node;
b->data=num;
b->next=nullptr;
a->next=b;
return ;
}
//从指定位置前插入
void push_assign(List a,int loc,int num)
{
int i=1;
if(loc>get_length(a)+1)
{
cout<<"over the lengthen!"<<endl;
return ;
}
while(i<loc)
{
a=a->next;
++i;
}
List b=new node;
b->data=num;
b->next=a->next;
a->next=b;
return ;
}
//连接两个链表
void add_List(List a,List b)
{
while(a->next)
a=a->next;
a->next=b->next;
return ;
}
int main()
{
List l=new node;
l->data=0;
l->next=nullptr;
List k=new node;
k->data=0;
k->next=nullptr;
//分布创建两个单链表,连接他们;
creat_List(l,2);
get_List(l);
push_assign(l,3,100);
get_List(l);
cout<<get_length(l);
creat_List(k,3);
add_List(l,k);
get_List(l);
return 0;
}