为了不像数组指针的增删操作还要判断是不是增删在的位置是头结点,现在引入一个方法,无论在什么位置都能够进行所有的增删改查操作。就是建立一个新的头结点,在这个结点中不存放任何数值和内容,用来当作头结点
提示:对于链表的内容如果不是很理解就尝试画出来链表更便于理解
#include <stdio.h>
#include <stdlib.h>
/*typedef struct student{
int num;
char name[20];
} ElemType; */
typedef int ElemType;
struct Node{
ElemType data;
struct Node * next;
};
void insert(struct Node *p ,int site,ElemType e);
void dele(struct Node *p,int site);
void output(struct Node *p);
void create(struct Node *p);
struct Node * find(struct Node *p,ElemType e);
void update(struct Node *p,int site,ElemType e);
int main()
{
struct Node *head,*q;
int i;
head=(struct Node *)malloc(sizeof(struct Node));
create(head);
output(head);
insert(head,1,4);
output(head);
insert(head,0,8);
output(head);
dele(head,3);
output(head);
q=find(head,3);
if(q!=NULL)
{
printf("find %d\n",q->data);
}
else{
printf("not find");
}
update(head,2,100);
output(head);
}
void create(struct Node *p)//创建链表
{
struct Node *n;
int i;
for(i=0;i<3;i++)
{
n=(struct Node *)malloc(sizeof(struct Node));
n->data=1+i;
n->next=NULL;
p->next=n;
p=n;
}
}
void insert(struct Node *p ,int site,ElemType e)//site为结点的位置,结点的位置从0开始标记
{
int i;
struct Node *n=(struct Node *)malloc(sizeof(struct Node));
n->data=e;
for(i=0;i<site;i++)//将p定位到插入位置site前面的一个结点
{
p=p->next;
}
n->next=p->next;
p->next=n;
}
void dele(struct Node *p,int site)//减
{
int i;
for(i=0;i<site;i++)
{
p=p->next;
}
p->next=p->next->next;
}
void output(struct Node *p)//输出
{
for(p=p->next;p!=NULL;p=p->next)
{
printf("%d,",p->data);
}
printf("\n");
}
struct Node * find(struct Node *p,ElemType e)//查
{
for(p=p->next;p!=NULL;p=p->next)
{
if(p->data==e)
return p;
}
return NULL;
}
void update(struct Node *p,int site,ElemType e)//改
{
int i=0;
for(;i<=site;i++)
p=p->next;
p->data=e;
}
这个是静态链表,是特别不灵活的,所以下一篇博客会介绍如何正确使用动态链表进行动态链表的增删改查功能,使链表的增删改查更加灵活