2017-09-11 LeetCode_024 Swap Nodes in Pairs

24. Swap Nodes in Pairs

Given a linked list, swap every two adjacent nodes and return its head.

For example,
Given 1->2->3->4, you should return the list as 2->1->4->3.

Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.


solution:

class Solution {
2
public:
3
    ListNode* swapPairs(ListNode* head) {
4
        if (head == NULL || head->next == NULL) return head;
5
        ListNode *p = head;
6
        head = head->next;
7
        p->next = swapPairs(head->next);
8
        head->next = p;
9
        return head;
10
    }
11
};










發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章