标签:解法 alt pair int next .com lin etc 技术
Swap Nodes in Pairs - LeetCode
解法一:维护三个指针,前中后,调换这三个位置的next指针即可。时间复杂度O(n)
/**
* 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) return NULL;
auto p = new ListNode(0);
p->next = head;
ListNode* pre = p;
ListNode* cur = head;
ListNode* next = head->next;
while(cur != NULL && cur->next != NULL)
{
pre->next = next;
cur->next = next->next;
next->next = cur;
pre = cur;
cur = cur->next;
if(cur != NULL)
next = cur->next;
}
return p->next;
}
};
Swap Nodes in Pairs - LeetCode
标签:解法 alt pair int next .com lin etc 技术
原文地址:https://www.cnblogs.com/multhree/p/10357247.html