链表成对交换问题

要求

给定一个链表1->2->3->4,你会返回2->1->4->3

代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <iostream>
using namespace std;
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;
        }else{
            ListNode* newHead = new ListNode(0);
            ListNode* pre = head;
            ListNode* p = pre->next;
            ListNode* next = NULL;
            ListNode* nh = newHead;
            while (p!=NULL) {
                next = p->next;
                p->next = pre;
                pre->next = next;
                nh->next = p;
                nh = pre;
                if (next==NULL) {
                    break;
                }
                pre = next;
                p = pre->next;

            }
            return newHead->next;
        }
    }
};
int main(int argc, const char * argv[]) {
    // insert code here...
    std::cout << "Hello, World!\n";
    return 0;
}

Comments