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

题目:

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

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

Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.

题意:给定一个链表,交换相邻的两个节点,交换节点而不是交换值

分析:用指针的指针来作交换,Python需要新建一个虚拟的首节点,用强大的C指针就方便多了,不过确实比较考验指针的应用能力啊。

CPP代码:

class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        ListNode** cur = &head;
        while ((*cur) && (*cur)->next) {
            ListNode* t = (*cur)->next;
            (*cur)->next = (*cur)->next->next;
            t->next = *cur;
            *cur = t;
            cur = &(*cur)->next->next;
        }
        return head;
    }
};

作弊CPP代码:

class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        ListNode *p = head;
        while(p && p->next) {
            swap(p->val, p->next->val);
            p = p->next->next;
        }
        return head;
    }
};

欢迎留言