链表由节点构成;表头+结点+表尾
节点:就是一个特殊的结构体,有两部分组成,一部分是数据域(该结点数据),另一部分是指针域(下一结点的首地址);
节点的定义:
链表的基本操作有:创建链表、查找、插入、删除和修改等。
创建链表具体操作:
#include<stdio.h>
#include<stdlib.h>
struct node{
int num;
struct node*next;
};
typedef struct _list{
struct node*head;
struct node*tail;
int n;
}List;
void add(List*list,int number);
int main()
{
int number;
List list;
list.n=0;
list.head=NULL;
list.tail=NULL;
do{
scanf("%d",&number);
if(number!=-1)
{
add(&list,number);
}
}
while(number!=-1);
list.head=fan(&list);
struct node*p;
for(p=list.head;p;p=p->next)//这里是输出
printf("%d ",p->num);
freelist(&list);
}
void add(List*list,int number)
{
list->n++;
struct node*p=(struct node*)malloc(sizeof(struct node));
p->num=number;
p->next=NULL;
if(list->n==1)
list->head=p;
else list->tail->next=p;
list->tail=p;
}
插入到第n个结点后(包括头结点):
struct node*p;
struct node*need;需要插入的结点;
need->num=
need->next=NULL;
p=xp;//xp为虚拟头结点,可在此之前设置
while(n--)
{
p=p->next;
}
need->next=p->next;
p->next=need;//此时要注意顺序
删除元素:
struct node*xp;
xp->next=list.head;
for(p=xp;p->next;p=p->next)
{
if(p->next->num==target)//目标值
p->next=p->next->next;
}
return xp->next;
!这里需要返回xp->next因为头结点可能被删除
删除第n个节点可参考这两个。
不管是删除还是插入我们都需要找到操作位置的前一个结点,可访问下一个结点