24.Swap Nodes in Pairs¶
Tags: Medium
Linked List
Links: https://leetcode.com/problems/swap-nodes-in-pairs/
Given a linked list, swap every two adjacent nodes and return its head.
You may not modify the values in the list's nodes, only nodes itself may be changed.
Example:
Given 1->2->3->4, you should return the list as 2->1->4->3.
/**
* 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 == NULL || head -> next == NULL) return head;
ListNode *dummy = new ListNode(0);
dummy -> next = head;
ListNode *pre = dummy -> next, *cur = pre -> next, *head2 = dummy;
bool flag = false;
while(pre -> next && cur -> next){
pre -> next = cur -> next;
cur -> next = head2 -> next;
head2 -> next = cur;
pre = pre -> next;
cur = pre -> next;
head2 = head2 -> next -> next;
if (cur == NULL){
flag = true;
break;
}
}
if (flag) return dummy -> next;
else{
pre -> next = cur -> next;
cur -> next = head2 -> next;
head2 -> next = cur;
}
return dummy -> next;
}
};
考虑个数为奇数的情形,采用一个flag
来记录是否出现奇数情形。方法主要就是交换节点,除了pre, cur
外,还需要一个head2
来记录pre
前面的节点。