鱼C论坛

 找回密码
 立即注册

两个循环链表的合并(附注解)

已有 132 次阅读2019-8-17 10:58

#include <stdio.h>
#include <stdlib.h>
typedef struct node {
    int data ;
    struct node *next ;
} node ;

node *create (node *head); // 创建循环链表
void display (node *tail); // 打印循环链表
node *combine (node *left , node *right); // 合并循环链表

int main ()
{
    node *list1 = NULL ;
    node *list2 = NULL ;
    node *list3 = NULL ;
    printf("请录入两个循环链表:\n");
    list1 = create(list1) ;
    list2 = create(list2) ;
    display(list1);
    display(list2);
    printf("合并两个循环链表:\n");
    list3 = combine(list1 , list2);
    display(list3);
    return 0 ;
}

node *create (node *head)
{
    node *target = NULL ;
    node *tail = NULL ;
    int input = 1 ;
    while (1)
    {
        scanf("%d",&input);
        if (input == 0)
        {
            return tail ; // 返回尾结点
        }
        else
        {
            if (head == NULL) // 第一次插入结点
            {
                head = (node *)malloc(sizeof(node)); // 动态分配内存
                head->next = head ; // 形成闭合循环链表
                head->data = -1 ; // 头结点不存数据,-1代表不存数据
                tail = head ; // 既是头结点,也是尾结点
            }
            for (target = head ; target->next != head ; target = target->next); // 找到当前尾结点
            tail = (node *)malloc(sizeof(node));
            tail->data = input ;
            target->next = tail ; // 将当前的尾结点指向新的结点
            tail->next = head ; // 再用新的结点指向头结点,成为新的尾结点
        }
    }
}

void display (node *tail)
{
    node *target = NULL ;
    while (1)
    {
        for (target = tail->next ; target->next != tail->next ; target = target->next)
        // 打印除了尾结点外的全部结点
        {
            printf("%d  ",target->data);
        }
        printf("%d\n",target->data); // 打印尾结点
        return ;
    }
}

node *combine (node *left , node *right)
{
    node *tmp = left->next ; // 录入第一链表的头结点
    left->next = right->next->next ;
    // right->next 就是第一链表的头结点,但不存数据,所以还要再步进找到存储数据的第一个结点
    free(right->next); // 释放第二链表的头结点
    right->next = tmp ; // 第二链表的尾结点接上第一链表的头结点,形成闭环
    return right ; // 返回整条链表的尾结点
}

路过

鸡蛋

鲜花

握手

雷人

评论 (0 个评论)

facelist

您需要登录后才可以评论 登录 | 立即注册

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-4-19 06:35

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

返回顶部