题目描述:将一个带头结点的单链表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)
代码实现:
#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 为 NULLtailA->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 -> 5LinkedList 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;
}