Leetcode#24 Swap Nodes in Pairs

来源:互联网 发布:网络话飞机场什么意思 编辑:程序博客网 时间:2024/04/28 18:55

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.

Difficulty: Medium


ListNode* swapPairs(ListNode* head) {        ListNode* first;        ListNode* second;        ListNode* third;        ListNode* temp = new ListNode(0);;        ListNode* beg;        if(!head || !head -> next) {         return head;     }        first = head;        beg = head->next;        while(first &&first->next)        {            third = first->next->next;            second = first->next;            temp ->next = second;            first->next = second->next;            second->next = first;             temp = first;            first = first->next;        }        return beg;    }


0 0