数据结构每日一题day15(链表)★★★★★

题目描述:将一个带头结点的单链表A分解为两个带头结点的单链表A和 B,使得A表中含有原表中序号为奇数的元素,而B表中含有原表中序号为偶数的元素,且保持相对顺不变,最后返回 B 表。

算法思想:

1.初始化:

创建新链表 B 的头结点。

定义指针 p 遍历原链表 A,tailA 指向 A 的当前尾节点,tailB 指向 B 的当前尾节点。

使用计数器 count 标记当前节点的序号(从 1 开始)。

2.遍历原链表:

如果 count 为奇数,将当前节点保留在 A 中,并更新 tailA。

如果 count 为偶数,将当前节点移动到 B 中,并更新 tailB。

每次处理后,p 后移,count 递增。

3.修正尾指针:

遍历结束后,确保 A 和 B 的尾节点的 next 均为 NULL。

4.返回链表 B。

复杂度分析:

时间复杂度:O(n)

空间复杂度:O(1)

代码实现:

cpp 复制代码
#include <stdio.h>
#include <stdlib.h>

typedef struct Node {
    int data;
    struct Node *next;
} Node, *LinkedList;

// 分解链表 A,返回链表 B
LinkedList splitList(LinkedList A) {
    LinkedList B = (LinkedList)malloc(sizeof(Node)); // 创建 B 的头结点
    B->next = NULL;
    Node *p = A->next;    // 遍历原链表的指针
    Node *tailA = A;      // A 的尾指针
    Node *tailB = B;      // B 的尾指针
    int count = 1;        // 节点序号计数器
    while (p != NULL) {
        if (count % 2 == 1) {
            // 奇数序号:保留在 A 中
            tailA->next = p;
            tailA = p;
        } else {
            // 偶数序号:移动到 B 中
            tailB->next = p;
            tailB = p;
        }
        p = p->next;
        count++;
    }
    // 确保 A 和 B 的尾节点 next 为 NULL
    tailA->next = NULL;
    tailB->next = NULL;
    return B;
}

// 打印链表
void printList(LinkedList L) {
    Node *p = L->next;
    while (p != NULL) {
        printf("%d ", p->data);
        p = p->next;
    }
    printf("\n");
}

int main() {
    // 创建测试链表 A: 1 -> 2 -> 3 -> 4 -> 5
    LinkedList A = (LinkedList)malloc(sizeof(Node));
    Node *node1 = (Node *)malloc(sizeof(Node));
    Node *node2 = (Node *)malloc(sizeof(Node));
    Node *node3 = (Node *)malloc(sizeof(Node));
    Node *node4 = (Node *)malloc(sizeof(Node));
    Node *node5 = (Node *)malloc(sizeof(Node));

    A->next = node1;
    node1->data = 1; node1->next = node2;
    node2->data = 2; node2->next = node3;
    node3->data = 3; node3->next = node4;
    node4->data = 4; node4->next = node5;
    node5->data = 5; node5->next = NULL;

    printf("原链表 A: ");
    printList(A);

    LinkedList B = splitList(A);

    printf("分解后 A (奇数序号): ");
    printList(A);
    printf("分解后 B (偶数序号): ");
    printList(B);

    // 释放内存(实际使用时需完善)
    free(A); free(B);
    free(node1); free(node2); free(node3); free(node4); free(node5);

    return 0;
}
相关推荐
王禄DUT2 小时前
高维亚空间超频物质变压缩技术 第27次CCF-CSP计算机软件能力认证
数据结构·算法
freyazzr3 小时前
Leetcode刷题 | Day51_图论03_岛屿问题02
数据结构·c++·算法·leetcode·深度优先·图论
passionSnail3 小时前
《MATLAB实战训练营:从入门到工业级应用》工程实用篇-自动驾驶初体验:车道线检测算法实战(MATLAB2016b版)
算法·matlab·自动驾驶
2301_807611493 小时前
126. 单词接龙 II
c++·算法·leetcode·深度优先·广度优先·回溯
奋进的小暄4 小时前
数据结构(4) 堆
java·数据结构·c++·python·算法
珊瑚里的鱼4 小时前
LeetCode 102题解 | 二叉树的层序遍历
开发语言·c++·笔记·算法·leetcode·职场和发展·stl
_Djhhh5 小时前
【基础算法】二分查找的多种写法
java·数据结构·算法·二分查找
王哥儿聊AI6 小时前
GenCLS++:通过联合优化SFT和RL,提升生成式大模型的分类效果
大数据·人工智能·深度学习·算法·机器学习·自然语言处理
xiaolang_8616_wjl6 小时前
c++_2011 NOIP 普及组 (1)
开发语言·数据结构·c++·算法·c++20