Swap Nodes in Pairs 题解
原创文章,拒绝转载
题目来源:https://leetcode.com/problems/swap-nodes-in-pairs/description/
Description
Given a linked list, swap every two adjacent nodes and return its head.
Example
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.
Solution
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
if (head == NULL)
return NULL;
ListNode *tempHead = new ListNode(0);
tempHead -> next = head;
ListNode* front = tempHead;
ListNode *node1, *node2;
while (front -> next && front -> next -> next) {
node1 = front -> next;
node2 = node1 -> next;
front -> next = node2;
node1 -> next = node2 -> next;
node2 -> next = node1;
front = node1;
}
ListNode* res = tempHead -> next;
delete tempHead;
return res;
}
};
解题描述
这道题题意是将一个链表中每相邻的一对节点交换位置(已经交换过位置的不再交换)。主要的想法是,每次有三个指针front
,node1
,node2
,在链表中是以front -> node1 -> node2
的顺序排列,这里主要要做的就是交换node1
和node2
的位置,使这段链表变成front -> node2 -> node1
,之后将node1
赋值给front
即可开始下一步交换。
另外这里用到了一个临时链表头tempHead
来指向原来的head
,便于给front
赋初始值,并且在返回新链表头的时候可以快速找到。