有序单向链表的相关操作

#include <stdio.h>

#include <malloc.h>

struct node    //节点的数据结构

{

    int num;

    struct node *next;

};

--- --- --- --- --- --- --- 插 入 --- --- --- --- --- --- ---

struct node *insert_node(struct node *head, int n)

{

    struct node *p1,*p2,*p3;

    p1 = (struct node *)malloc(sizeof(struct node));

    (*p1).num = n;

    if (head == 0)  {  head = p1; (*p1).next = 0; } //空链表

    else   //非空链表

    {

        p2 = head;

        while (n>(*p2).num && (*p2).next!=0)

            { p3 = p2;  p2 = (*p2).next; }

        if (n > (*p2).num)   //插在链表尾(p2后面)

            { (*p2).next = p1;  (*p1).next = 0; }

        else

        {   //插在链表头(p2前面)

            if (p2 == head)  { head = p1;  (*p1).next = p2; }

            else     //插在链表中(p2p3之间)

                { (*p3).next = p1; (*p1).next = p2; }

        }

    }

    return head;

}

--- --- --- --- --- --- --- 删 除 --- --- --- --- --- --- ---

struct node *delete_node(struct node *head, int n)

{

    struct node *p1,*p2;

    if (head==0) printf("/nList is null!/n"); //空链表

    else

    {

        p1 = head;

        while((*p1).num!=n && (*p1).next!=0)

            { p2 = p1;  p1 = (*p1).next; }

        if ((*p1).num == n)  //找的到

        {

            if(p1 == head)  head = (*head).next; //要删的是链表

            else  (*p2).next = (*p1).next;  //其他位置         

         // free(p1) ;

        }

        else printf("/nNot found!/n"); //找不到

    }

    return(head);

}

--- --- --- --- --- ---  链 表 反 转  --- --- --- --- --- ---

struct node *inverse(struct node *head)

{

    struct node *p1,*p2,*p3;

    p1 = (*head).next; p2 = head; (*p2).next = 0; p3 = p2;

    while(p1)

    { p2 = p1; p1 = (*p1).next; (*p2).next = p3; p3 = p2; }

    head = p2; return head;

}

--- --- --- --- --- --- --- 调 用 --- --- --- --- --- --- ---

void main()

{

    struct node a,b,c,d,*head,*p;

    a.num = 8; a.next = &b; b.num = 6; b.next = &c;

    c.num = 4; c.next = &d; d.num = 2; d.next = 0;  head = &a;

    head = inverse(head);

    head = insert_node(head,7);

    head = delete_node(head,2);

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值