LeetCode 24. 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.

题目要求成对翻转指针,难度一般,要求使用常数的空间,应当使用迭代的方法而非递归的方法,这里我们加上一个头结点dummy,这样一来即使翻转的节点涉及到头结点,需要修改头指针,我们也可以做到和一般节点一样处理,我们设置了一个指针pre指向“一对”节点,一个指针t指向一对节点的第二个节点

【图解稍后补充】

代码如下:

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     ListNode* swapPairs(ListNode* head) {
12         ListNode *dummy = new ListNode(-1), *pre = dummy;
13         dummy->next = head;
14         while (pre->next && pre->next->next)
15         {
16             ListNode *t = pre->next->next;
17             pre->next->next = t->next;
18             t->next = pre->next;
19             pre->next = t;
20             pre = t->next;
21         }
22         return dummy->next;
23     }
24 };
原文地址:https://www.cnblogs.com/dapeng-bupt/p/8169113.html