链表交错c++解法

题目

将链表
1->2->3->4->5->6->7…->n-1->n
变为
1->n->2->n-1->…

请使用原地变化。

解法

  1. 首先,使用快慢指针,得到链表的中心节点
  2. 然后,从slow指针指向的位置开始反转后半段链表
  3. 然后对两个链表执行交错指向

代码

#include <iostream>

using namespace std;

struct Node {
    int val;
    Node *next;

    Node(int _val) {
        val = _val;
        next = nullptr;
    }
};

Node *func(Node *node) {
    Node *slow = node;
    Node *fast = node;

    while (fast != nullptr && fast->next != nullptr) {
        slow = slow->next;
        fast = fast->next->next;
    }

    Node *p1 = node;
    Node *p2 = nullptr;

    Node *pre = nullptr;
    Node *cur = slow;
    while (cur != nullptr) {
        Node *tmp = cur->next;

        cur->next = pre;
        pre = cur;

        cur = tmp;
    }

    p2 = pre;

    while (p2->next != nullptr) {
        auto tmp = p1->next;
        p1->next = p2;

        auto tmp_p2_next = p2->next;
        p2->next = tmp;

        p1 = tmp;
        p2 = tmp_p2_next;
    }

    return node;
}

int main() {
    // char str[3];
    // std::cin>>str;
    std::cout << "hello world" << std::endl;

    int N = 10;

    Node *root = new Node(1);

    Node *p = root;
    for (auto i = 2; i <= 10; i++) {
        Node *node = new Node(i);
        p->next = node;
        p = p->next;
    }

    auto res = func(root);

    p = res;
    while (p != nullptr) {
        std::cout << p->val << "->";
        p = p->next;
    }

    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值