leetcode-24 Swap Nodes in Pairs

来源:互联网 发布:car软件 编辑:程序博客网 时间:2024/06/06 09:17
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.


//////////////////////////////////////////////////////////////////////////
// start: swap every two adjacent nodes of a lined list
// 注:需要三个指针来交换相邻两个node
ListNode *swapPairs(ListNode *head)
{
    if(head == NULL || head->next == NULL)  // 空和一个元素
        return head;

    ListNode result(-1);
    result.next = head;
    for(ListNode *pre = &result, *cur = pre->next, *next = cur->next; next != NULL; pre = cur, cur = cur->next, next = (cur != NULL ? cur->next : NULL))  // 三个指针,当前指针,下一个要交换的指针,以及当前的上一个指针
    {
        pre->next = next;  // 交换current和next
        cur->next = next->next;
        next->next = cur;
    }
    return result.next;
}
// end
//////////////////////////////////////////////////////////////////////////
0 0