一个C语言的题目 求解答啊 急用

2025-02-23 09:14:48
推荐回答(1个)
回答1:

楼主你好~


代码如下,附件附上,请笑纳。


#include 

#include 

#define Insert(a,b) b->next = a->next; a->next =b // 在a后插入b

#define InsertTail(h,b) h->tail->next = b; h->tail = b // 在链表尾插入结点

typedef struct mNode* pNode;

typedef struct mNode

{

    pNode next;

    union

    {

        int content;    // 使用联合体,头结点内容为尾结点地址,普通结点内容为整形数

        pNode tail;

    };

}myNode;

// 在某个值结点之前插入结点

void InsertBefore(myNode* head, int contentRes, int contentInsert)

{

    while(NULL != head->next)

    {

        if(head->next->content == contentRes)

        {

            myNode* _add;

            _add = (myNode*)malloc(sizeof(myNode));

            _add->content = contentInsert;

            _add->next = NULL;

            Insert(head, _add);

            break;

        }

        head = head->next;

    }

}

// 在链表尾插入值

void AddContentToTail(myNode* head, int content)

{

    myNode* _add;

    _add = (myNode*)malloc(sizeof(myNode));

    _add->content = content;

    _add->next = NULL;

    InsertTail(head, _add);

}

// 遍历打印链表

void printList(myNode* node)

{

    if(NULL != node)

    {

        printf("%d\n", node->content);

        printList(node->next);

    }

}

int main()

{

    myNode* head;

    head = (myNode*)malloc(sizeof(myNode));

    head->tail = head;

    head->next = NULL;

    AddContentToTail(head, 7);

    AddContentToTail(head, 8);

    AddContentToTail(head, 9);

    AddContentToTail(head, 10);

    AddContentToTail(head, 11);

    printList(head->next);

    printf("\n");

    InsertBefore(head, 10, 20);

    printList(head->next);

    printf("\n");

    InsertBefore(head, 11, 30);

    printList(head->next);

    return 0;

}


请追问~!