#include<stdio.h>
#include<stdlib.h>
struct node
{
int num;
struct node *next;
};
struct node *head=NULL;
cre_list() //初始化结点
{
head = (struct node *)malloc(sizeof(struct node));
head->next = NULL;
}
add_node(int num) //插入结点
{
struct node *ptr = (struct node *)malloc(sizeof(struct node));
ptr->num = num;
ptr->next = head;
head=ptr;
}
add_five_node(int num) //在5之后插入结点
{
int i = 0;
struct node *p,*q;
p=head;
q=head;
struct node *ptr = (struct node *)malloc(sizeof(struct node));
ptr->num = num;
while((p->num)!=5)
{
p = p->next;
}
ptr->next=p->next;
p->next=ptr;
}
struct node *opp_node(struct node *head)//链表逆序
{
struct node *p,*front,*q;
front=NULL;
p=head;
while(p!=NULL)
{
q=p->next;//尾插入法
p->next=front;
front=p;
p=q;
}
head =front;
return head;
}
display_node() //遍历链表
{
struct node *p = head;
do
{
printf("%d\t",p->num);
p = p->next;
}while(p != NULL);
printf("\n");
}
delete_node() //删除偶数结点
{
struct node *p,*q;
p = head;
q = head->next;
while(q != NULL)
{
if((q->num)%2 == 0)
{
p->next=q->next;
free(q);
q=p->next;
continue;
}
p = p->next;
q = q->next;
}
if((head->num)%2 == 0)
{
p = head;
head = head->next;
free(p);
p = NULL;
}
}
int main()
{
int i=0;
cre_list();
for(i;i<10;i++)
{
add_node(i);
}
display_node();
add_five_node(12);
add_five_node(14);
add_five_node(16);
add_five_node(18);
display_node();
delete_node();
display_node();
head=opp_node(head);
display_node();
return 0;
}
链表删除偶结点时,head结点暂不考虑,利用两个指针删除从第二个结点开始的偶结点,待删除完之后,再回头判断头结点是否为偶数,若为偶数则删除头结点。