优点:
节省空间,添加节点时,必须再次申请新的内存空间
插入删除方便
插入
p为要插入的结点
pre为前结点
1.p->next = pre->next (后)
2. pre->next = p
删除
p为要删除的饿结点
1.pre->next = p->next
2. free p
缺点:
使用时必须从头节点遍历,找到某个节点,无法随机读取
#include"stdio.h"
#include"stdlib.h"
typedef struct 链表
{
/* data */
int data;
LB next;
}*LB;
LB init_lb()
{
LB head;
head = (LB)malloc(sizeof(LB));
head->next = NULL;
return head;
}
void Input_LinkList1(LB head)
{
int data;
LB r;
r = head;
printf("请输入\n");
scanf("%d",&data);
while(data!=0)
{
LB p;
p = (LB)malloc(sizeof(LB)); //申请新的结点
p->data = data; //结点数据域赋值
r->next = p; //将结点插入到表头L-->|1|-->|2|-->NULL
r = p;
scanf("%d",&data);
}
r->next = NULL;
}
LB insert_lb(LB head,int loc,int num)
{
LB pre;
pre=head;
for(int i=0;i<loc;i++)
{
pre=head->next;
}
LB p;
p=(LB)malloc(sizeof(LB));
p->data=num;
p->next=pre->next;
pre->next=p;
return head;
}
LB delete_lb(LB head,int num)
{
if(head->next==NULL)
{
printf("空\n");
return;
}
else
{
LB p,pre;
while(p->data!=num)
{
if(p->next == NULL)
{
printf("未找到\n");
return;
}
pre=p;
p=p->next;
}
p->next=pre->next;
free(p);
}
}
void Output(LB head)
{
LB thi;
thi = head->next;
while(thi)
{
printf("%d",thi->data);
thi=thi->next;
}
}
int main()
{
LB head;
head = init_lb();
Input_LinkList1(head);
Output(head);
return 0;
}