24. Swap Nodes in Pairs

来源:互联网 发布:python windows 路径 编辑:程序博客网 时间:2024/05/29 11:58

题目:Swap Nodes in Pairs

原题链接: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.

给出一个单链表,将每两个连续的节点逆置一下。
例如1->2->3->4,返回2->1->4->3.
要求只能使用常数级空间,并且不能修改节点的元素值,只能修改节点本身。

假设现在有4个连续的节点1->2->3->4, ,我们要逆置2->3的话,我们需要知道 1和 4 ,不然的话链表会断开,所以用pre表示当前要逆置的节点块之前一个节点,temp表示要节点块接下来的一个节点,next1表示节点块中的第一个节点,next2表示节点块中第二个节点。
那么我们只需要:
pre->next = next2;
next2->next = next1;
next1->next = temp;
即可。
另外对于头两个节点,由于没有pre,所以要单独先把他们处理一下,之后的节点可以用循环来做。

代码如下:

/** * 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 == NULL) return head;        ListNode *pre, *next1, *next2, *temp;        temp = head->next->next;        next1 = head, next2 = head->next;        head = next2, head->next = next1;        next1->next = temp, pre = next1;        while(pre->next && pre->next->next) {            next1 = pre->next, next2 = next1->next, temp = next2->next;            pre->next = next2;            next2->next = next1;            next1->next = temp;            pre = next1;        }        return head;    }};
0 0