链接
https://leetcode-cn.com/problems/swap-nodes-in-pairs/
耗时
解题:17 min
题解:2 min
题意
给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
思路
详见代码,不好叙述,画一遍就懂了。
时间复杂度: O ( n ) O(n) O(n)
AC代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
if(head == NULL || head->next == NULL) return head;
ListNode* res = head->next;
ListNode* pre = head;
ListNode* post = head;
while(pre != NULL && pre->next != NULL) {
post->next = pre->next;
post = pre->next;
pre->next = post->next;
post->next = pre;
post = pre;
pre = pre->next;
}
return res;
}
};