list swap pairs

leetcode 24

/**
 * 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 = head;
        while(p)
        {
            if(p->next)
            {
                swap(p->val,p->next->val);
                p = p->next->next;
            }
            else
            {
                break;
            }
        }
        return head;
    }
};

你可能感兴趣的:(数据结构与算法,数据结构与算法)