leetcode:
https://leetcode-cn.com/problems/swap-nodes-in-pairs/
MyCode: 双指针:
#pragma once
#include <iostream>
//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 (nullptr == head) {
return head;
}
ListNode* pRear = head;
ListNode* pFront = head->next;
while (pFront && pRear) //嗯 判断条件是个坎,想出了就好
{
//swap
int temp = pFront->val;
pFront->val = pRear->val;
pRear->val = temp;
pRear = pFront->next;
if (pFront->next) {
pFront = pFront->next->next;
}
else
break;
}
return head;
}
void pintfList(ListNode* pHead)
{
if (nullptr == pHead)
return;
ListNode* p = pHead;
while (p)
{
std::cout << p->val<<" ";
p = p->next;
}
std::cout << "\n ";
}
void Test() {
ListNode* pHead = new ListNode(1);
pHead->next= new ListNode(2);
pHead->next->next = new ListNode(3);
pHead->next->next->next = new ListNode(4);
pHead->next->next->next->next = new ListNode(5);
pintfList(pHead);
ListNode* resHead = swapPairs(pHead);
pintfList(pHead);
}
};
int main()
{
Solution obj;
obj.Test();
return 0;
}
还有递归解法。