美文网首页
24. Swap Nodes in Pairs

24. Swap Nodes in Pairs

作者: jecyhw | 来源:发表于2019-05-21 15:14 被阅读0次

题目链接

https://leetcode.com/problems/swap-nodes-in-pairs/

解题思路

直接看代码

代码

class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        if (head == NULL || head->next == NULL) {
            return head;
        }
        ListNode *first = head, *next, *end, *t;
        head = NULL;

        while (first != NULL && first->next != NULL) {
            //next和first交换
            next = first->next;
            t = next->next;
            next->next = first;
            first->next = t;

            if (head == NULL) {
                head = next;
            } else{
                end->next = next;
            }
            end = first;
            first = t;

        }
        return head;
    }
};

相关文章

网友评论

      本文标题:24. Swap Nodes in Pairs

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