美文网首页链表
【leetcode】24. Swap Nodes in Pair

【leetcode】24. Swap Nodes in Pair

作者: 邓泽军_3679 | 来源:发表于2019-05-12 23:50 被阅读0次

1、题目描述

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

You may not modify the values in the list's nodes, only nodes itself may be changed.

Example:

Given 1->2->3->4, you should return the list as 2->1->4->3.

2、问题描述:

  • 成对的交换,不能改动结点的值。

3、问题关键:

4、C++代码:

/**
 * 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 || !head->next) return head;
        auto p = head;
        auto dummy = new ListNode(-1), pre = dummy;
        while(p && p->next) {
            auto t = p->next->next;
            pre->next = p->next;
            p->next->next = p;
            p->next = t;
            pre = p, p = t;
        }
        return  dummy->next;
    }
};

相关文章

网友评论

    本文标题:【leetcode】24. Swap Nodes in Pair

    本文链接:https://www.haomeiwen.com/subject/xalxaqtx.html