[系列文章] leetcode每日一题24

发布于 28 天前  141 次阅读


leetcode 24 swap nodes in pairs

Description

Given a linked list, swap every two adjacent nodes and return its head.

Solution

思路很明确,交换节点的指向关系,非相邻交换而是成对交换,遍历时跳跃式前进即可。

Code

/**
 * 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) return nullptr;
        ListNode* current = head;
        ListNode* advance = head->next;
        ListNode* previous = nullptr;
        head = nullptr;
        while (current && advance) {
            current->next = advance->next;
            advance->next = current;
            if (previous) previous->next = advance;
            if (head == nullptr) head = advance;
            previous = current;
            current = current->next;
            if (current) advance = current->next;
        }
        return head ? head : current;
    }
};

一只在互联网躬耕的菜鸟,写代码是热爱,二次元也是,mikoto也是