week10-leetcode #24-Swap-Nodes-in-Pairs
链接:https://leetcode.com/problems/swap-nodes-in-pairs/description/
Question
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.
Solution
time complecity: O(n)
space complecity: O(n)
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
int pre_val = 0;
int post_val = 0;
ListNode* p = head;
// 不断往前交换数据
while (p != NULL && p->next != NULL) {
pre_val = p->val;
post_val = p->next->val;
p->val = post_val;
p->next->val = pre_val;
p = p->next->next;
}
return head;
}
};
思路:本题目只对偶数对进行处理,也就是(0,1)、(2,3)、(4,5)等进行配对(下标从0开始),最后的奇数即可以直接忽略不处理。