单链表分为带头节点和不带头节点两种类型
相比之下带头节点的链表相对好写点
不带头节点的链表其实就是用一个结构体指针直接指向第一个节点
带头节点的其实就是用一个结构体的指针域指向第一个节点;
结构体的建立
struct node
{
int date;//数据域,不一定是int类型
struct node *next;//数据域
} a;
用typedef 简化代码
typedef struct
{
int date;
struct node *next;
} node,*LinkList;
node *p=(node *)malloc(sizeof(node))
LinkList p;
node *p;
这两个是等价的;
带头节点的链表插入操作
typedef struct
{
int date;
struct node *next;
} node,*LinkList;
node *p=(node *)malloc(sizeof(node));
bool Listinsert(LinkList &L,int i,int e)
{
if(i<1)
return false;
node *p;//指针p指向当前扫描的点
int j=0;//表示指向第几个点
p=L;
while(p!=NULL&&j<i-1)
{
p=p->next;
j++;
}
if(p==NULL)//i值过大不合法
return false;
node *s=(node*)malloc(sizeof(node));//申请
s->date=e;
s->next=p->next;//将节点s连接到p后
p->next=s;
return true;
}
不带头节点的链表
typedef struct
{
int date;
struct node *next;
} node,*LinkList;
node *p=(node *)malloc(sizeof(node));
bool Listinsert(LinkList &L,int i,int e)
{
if(i<1)
return false;
if(i==1)
{
node *p=(node *)malloc(sizeof(node));
p->date=e;
p->next=L;
L=p;
}
node *p;//指针p指向当前扫描的点
int j=1;//表示指向第几个点
p=L;
while(p!=NULL&&j<i-1)
{
p=p->next;
j++;
}
if(p==NULL)//i值过大不合法
return false;
node *s=(node*)malloc(sizeof(node));
s->date=e;
s->next=p->next;//将节点s连接到p后
p->next=s;
return true;
}