美文网首页
24. Swap Nodes in Pairs/两两交换链表中的

24. Swap Nodes in Pairs/两两交换链表中的

作者: 蜜糖_7474 | 来源:发表于2019-05-10 20:19 被阅读0次

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.

AC代码1

class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        ListNode *dummy = new ListNode(-1), *pre = dummy;
        dummy->next = head;
        while (pre->next && pre->next->next) {
            ListNode* t = pre->next->next;
            pre->next->next = t->next;
            t->next = pre->next;
            pre->next = t;
            pre = t->next;
        }
        return dummy->next;
    }
};

AC代码2

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

总结

没写出来,对链表很不熟悉,参考资料:https://www.cnblogs.com/grandyang/p/4441680.html

相关文章

网友评论

      本文标题:24. Swap Nodes in Pairs/两两交换链表中的

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