0
点赞
收藏
分享

微信扫一扫

leetcode-114. 二叉树展开为链表

前言

思路

思路还是挺清晰的,就是简单的模拟,但是一定要搞清楚交换的步骤,绕不清楚的时候最好画图来辅助解决问题。

代码

huatu

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        if (head == nullptr || head -> next == nullptr) return head;

        ListNode* dummyHead = new ListNode(0);
        dummyHead -> next = head;
        ListNode* cur = dummyHead;

        while (cur -> next != nullptr && cur -> next -> next != nullptr) {
            ListNode* tmp1 = cur -> next;
            ListNode* tmp2 = cur -> next -> next -> next;

            cur -> next = cur -> next -> next;
            cur -> next -> next = tmp1;
            cur -> next -> next -> next = tmp2;

            cur = cur -> next -> next;
        }

        head = dummyHead -> next;
        delete dummyHead;

        return head;
    }
};
  • 时间复杂度: O ( n ) O(n) O(n)
  • 空间复杂度: O ( 1 ) O(1) O(1)
举报

相关推荐

0 条评论