当前位置:   article > 正文

链表折叠C++_链表对折

链表对折

提示:链表创建、链表反转、链表合并,完整输入输出c++


题目分析

题目描述

给定一个单链表,将链表两两首尾相连,如1 2 3 4 5 6,变成1 6 2 5 3 4

题目分析

将链表拆分成两段,后一段反转之后,再将两端链表合并

具体步骤

  1. 创建链表
  2. 拆分链表
  3. 反转后一段链表
  4. 合并链表
  5. 输出链表

代码实现

//链表折叠
#include <iostream>

using namespace std;
struct listNode {
    int val;
    listNode* next;
    listNode(int value) :val(value), next(nullptr) {}
};

// 输入链表
void input(listNode* head, int num) {
    listNode* cur = head;
    for (int i = 1; i <= num; i++) {
        listNode* newNode = new listNode(i);
        cur->next = newNode;
        cur = cur->next;
    }
}
// 打印链表
void printList(const listNode* cur) {
    while (cur) {
        cout << cur->val << " ";
        cur = cur->next;
    }
    cout << endl;
}
//分割链表
listNode* findHalfhead(listNode* head, int num) {
    listNode* cur = head;
    listNode* halfHead = cur;
    for (int i = 0; i <= (num / 2); i++) {
        cur = cur->next;
        halfHead = cur;
    }
    return halfHead;
}
//反转链表
listNode* reverseList(listNode* head) {
    listNode* tmp(0);
    listNode* cur = head;
    listNode* pre = nullptr;
    while (cur) {
        tmp = cur->next;
        cur->next = pre;
        pre = cur;
        cur = tmp;
    }
    return pre;
}
//合并链表
listNode* combineList(listNode* head1, listNode* head2) {
    listNode* cur1 = head1;
    listNode* cur2 = head2;
    while (cur2->next) {
        listNode* tmp1 = cur1->next;
        listNode* tmp2 = cur2->next;
        cur1->next = cur2;
        cur2->next = tmp1;
        cur1 = tmp1;
        cur2 = tmp2;
    }
    return head1;
}

int main() {
    int num;
    cin >> num;

    listNode* head = new listNode(0);
    input(head, num);

    listNode* halfHead = findHalfhead(head, num);
    printList(head);
    printList(halfHead);
    listNode* end = reverseList(halfHead);
    printList(head);
    printList(end);

    listNode* finalHead = combineList(head, end);
    printList(finalHead);

    system("pause");
    return 0;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85

总结

复杂度:

时间复杂度:O(n)
空间复杂度:不分析了,引用的子函数较多
这一题考核的链表知识比较全面,算是将链表的创建、插入、删除、遍历都包括在内,是一道经典的链表综合题,在面试中经常遇到。


声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Monodyee/article/detail/661783
推荐阅读
相关标签
  

闽ICP备14008679号