Swap Nodes in Pairs - LeetCode

题目链接

Swap Nodes in Pairs - LeetCode

注意点

  • 考虑链表为空

解法

解法一:维护三个指针,前中后,调换这三个位置的next指针即可。时间复杂度O(n)

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        if(head == NULL) return NULL;
        auto p = new ListNode(0);
        p->next = head;
        ListNode* pre = p;
        ListNode* cur = head;
        ListNode* next = head->next;
        while(cur != NULL && cur->next != NULL)
        {
            pre->next = next;
            cur->next = next->next;
            next->next = cur;
            
            pre = cur;
            cur = cur->next;
            if(cur != NULL)
                next = cur->next;
        }
        return p->next;
    }
};

小结

  • 链表是很常见的一种数据结构,要花点时间专门研究一下。

猜你喜欢

转载自www.cnblogs.com/multhree/p/10357247.html