LeetCode24 Swap Nodes in Pairs

题目描述:
Given a linked list, swap every two adjacent nodes and return its head.

Example:

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

Your algorithm should use only constant extra space.
You may not modify the values in the list’s nodes, only nodes itself may be changed.
题源:here;完整代码:here
思路:
如果是换作交换两个整数的话我想没人会觉得有什么难度;但因为是链表,处理起来就显得麻烦一些,不过两者本质是一样的:通过一个中间变量暂存一个值,然后交换。说起来麻烦,看图就方便多了:
这里写图片描述
图上的标号显示的是执行的顺序
代码

class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        ListNode feakHead(0), *curr;
        feakHead.next = head; head = &feakHead; curr = head;

        while (curr->next && curr->next->next){
            ListNode *temp = curr->next;
            curr->next = curr->next->next;
            temp->next = curr->next->next;
            curr->next->next = temp;
            curr = curr->next->next;
        }

        return feakHead.next;
    }
};

猜你喜欢

转载自blog.csdn.net/m0_37518259/article/details/80716558