总论链表:链表作为一种重要的数据结构是算法入门的首选。
我们先讲定义链表,我们从结构体出发,在结构体中有一个相同类型的指针,它可以指向这个结构体所有的元素。
#include<bits/stdc++.h>//单向指针链表
using namespace std;
typedef struct node* ptrtonode;//将 struct node* 类型定义为ptrtonode
struct node
{
//char num[8];
//char name[8];
int score;
ptrtonode next;//一个结构体类型的指针
} ;
typedef ptrtonode ist;//同上
typedef struct node* ptrtonode;就是给struct node* 换个名字叫ptrtonode为了方便
在下面我们看到 ptrtonode next 这就是一个当前结构体类型的指针,你可以理解为 有 int* ,str*
而它是node *。
下面介绍头插法
void headinsert1( ist&head,int m )//头插法
{
ist tempre;
tempre= new node;//开辟一个指针的空间
tempre->score=m;
tempre->next=head;//将原来head为它的下一个节点
head=tempre;//将它设为头节点
}
非常简单就是每次从head 添加
下面是插入操作;
void insert( ist l,int x)//中间插入
{
// cout<<1;
ist tmp;//中间指针
tmp=(ptrtonode)malloc(sizeof(struct node));//申请一个结构体大小的结构体指针
while(l->next!=NULL)//当指针不为空时
{ if(x>=l->score)//判断l指向结构体的score是否小于等于x
{
//cout<<2;
tmp->score=x;//插入操作结构体指针指向的值为x
tmp->next=l->next;//l指向的下一个赋给tmp
l->next=tmp;//将l的下一个指向tmp
return ;}
l=l->next;
}
然后是删除操作
void del(ist head, int m )//删除操作
{
if(head->score==m)//判断头节点的值是否为删除点
head=head->next;//直接将head的下一个赋给head
else
{ ist p,w;//两个相同类型的指针
p=head;//p指向head
while(p->next!=NULL)
{
if(p->next->score==m)//判断p的下一个节点是否为所要删除的点
{
w=p->next;//w指向这个节点
p->next=p->next->next;//删除操作p的下两个节点变为下一节点
free(w);//释放当前空间
}
p=p->next;
}
}
}
下面是我的所有代码。
#include<bits/stdc++.h>//单向指针链表
using namespace std;
typedef struct node* ptrtonode;//将 struct node* 类型定义为ptrtonode
struct node
{
//char num[8];
//char name[8];
int score;
ptrtonode next;//一个结构体类型的指针
} ;
typedef ptrtonode ist;//同上
void insert( ist l,int x)//中间插入
{
// cout<<1;
ist tmp;//中间指针
tmp=(ptrtonode)malloc(sizeof(struct node));//申请一个结构体大小的结构体指针
while(l->next!=NULL)//当指针不为空时
{ if(x>=l->score)//判断l指向结构体的score是否小于等于x
{
//cout<<2;
tmp->score=x;//插入操作结构体指针指向的值为x
tmp->next=l->next;//l指向的下一个赋给tmp
l->next=tmp;//将l的下一个指向tmp
return ;}
l=l->next;
}
;
}
void del(ist head, int m )//删除操作
{
if(head->score==m)//判断头节点的值是否为删除点
head=head->next;//直接将head的下一个赋给head
else
{ ist p,w;//两个相同类型的指针
p=head;//p指向head
while(p->next!=NULL)
{
if(p->next->score==m)//判断p的下一个节点是否为所要删除的点
{
w=p->next;//w指向这个节点
p->next=p->next->next;//删除操作p的下两个节点变为下一节点
free(w);//释放当前空间
}
p=p->next;
}
}
}
void headinsert1( ist&head,int m )//头插法
{
ist tempre;
tempre= new node;//开辟一个指针的空间
tempre->score=m;
tempre->next=head;//将原来head为它的下一个节点
head=tempre;//将它设为头节点
}
int main()
{
ist head=NULL;//给head初始化保证最后一个节点指向空
for( int i=1;i<10;i++)//假设我们头插法
{
headinsert1(head,i);
}
insert( head,4);//从中间插入
ist opr;
opr=head;
del(head,5);//删除score为5的节点
while( opr->next!=NULL)//遍历所有节点并输出
{
printf("%d\n",opr->next->score);
opr=opr->next;
}
return 0;
}
希望对大家有用哈。