leetcode 24. Swap Nodes in Pairs

来源:互联网 发布:greenvpn网络加速器 编辑:程序博客网 时间:2024/05/29 03:02

相关问题

Discription

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.

思路

模拟题

时间复杂度:?
空间复杂度:?

代码

/** * 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) {        ListNode *pCur, *pNode2, *pNode3, *pHead;        if (!head || !head->next)            return head;        pHead = head->next;        pCur = head;                // 1        while (pCur && pCur->next)        {            pNode2 = pCur->next;    // 2            pNode3 = pNode2->next;  // 3            if (!pNode3 || !pNode3->next)                pCur->next = pNode3;            else                pCur->next = pNode3->next;            pNode2->next = pCur;            pCur = pNode3;        }        return pHead;    }};
原创粉丝点击