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.

 本文只需要两个指针依次交换相互位置。但是需要注意单数链表的情况。时间:4ms

代码如下:

/**
 * 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) {
        if (head == NULL || head->next == NULL)
            return head;
        ListNode *p, *q, *phead, *pnext=new ListNode(0);
        p = head;
        q = head->next;
        phead = pnext;
        do{
            q = p->next;
            p->next = q->next;
            q->next = p;
            pnext->next = q;
            pnext = p;
            if (p != NULL)
                p = p->next;
        } while (p != NULL&&p->next != NULL);
        return phead->next;
    }
};

 

posted on 2015-06-02 22:04  NealCaffrey989  阅读(123)  评论(0编辑  收藏  举报