C的链表实现

#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结点暂不考虑,利用两个指针删除从第二个结点开始的偶结点,待删除完之后,再回头判断头结点是否为偶数,若为偶数则删除头结点。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值