链表
链表是一种物理存储单元上非连续、非顺序的存储结构,数据元素的逻辑顺序是通过链表中的指针链接次序实现的。链表由一系列结点(链表中每一个元素称为结点)组成,结点可以在运行时动态生成。每个结点包括两个部分:一个是存储数据元素的数据域,另一个是存储下一个结点地址的指针域。
结构体
struct Test
{
int data;
struct Test *next;
};
前插法
struct Test *insertfrombefore(struct Test *head,int insert_data,struct Test *new)
{
struct Test *p = head;
if(p->data == insert_data){
new->next = head;
return new;
}
//遍历
while(p->next != NULL){
if(p->next->data == insert_data){
new->next = p->next;
p->next=new;
return head;
}
p = p->next;
}
printf("no this data %d\n",insert_data);
return head;
}
head:链表头节点
insert_data :被前插节点的值
new:新节点
后插法
struct Test *insertfrombehind(struct Test *head,int insert_data,struct Test *new)
{
struct Test *p = head;
while(p != NULL){
if(p->data == insert_data){
new->next = p->next;
p->next = new;
return head;
}
p = p->next;
}
printf("no this data %d\n",insert_data);
return head;
}
head:链表头节点
insert_data :被后插节点的值
new:新节点
头插法
struct Test *insertfromhead(struct Test *head)
{
struct Test *new = NULL;
while(1){
new =( struct Test *)malloc(sizeof(struct Test));
printf("please input new node(0 qiut)!\n");
scanf("%d",&new->data);
if(new->data == 0){
printf("quit\n");
return head;
}
if(head == NULL){
head = new;
}else{
new->next = head;
head=new;
}
}
return head;
}
尾插法
struct Test *insertfromtail(struct Test *head)
{
struct Test *new = NULL;
struct Test *p = head;
while(1){
new = (struct Test *)malloc(sizeof(struct Test));
printf("please input new node(0 quit)!\n");
scanf("%d",&new->data);
if(new->data == 0){
printf("quit\n");
return head;
}
if(p == NULL){
p = new;
head = p;
}else{
while(p->next != NULL){
p = p->next;
}
p->next = new;
}
}
return head;
}