LeetCode 24 - Swap Nodes in Pairs

一、问题描述

Description:

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.

Note:

Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.

给一个链表,交换每两个相邻的结点,返回新链表。


二、解题报告

解法一:操作值域

直接交换结点的val是最简单的:

class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        if(head == NULL)
            return NULL;
        ListNode* first = head;
        ListNode* second = head->next;
        while(first!=NULL && second!=NULL) {
            int temp = first->val;      // 交换val
            first->val = second->val;
            second->val = temp;
            if(first->next!=NULL)
                first = first->next->next;
            if(second->next!=NULL)
                second = second->next->next;
        }
        return head;
    }
};


解法二:操作结点

题目要求:You may not modify the values in the list, only nodes itself can be changed. 好吧,那就来操作结点吧。

class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        if(head == NULL)
            return NULL;
        ListNode* first = head;
        ListNode* second = head->next;
        ListNode* p = new ListNode(0);
        head = p;
        while(first!=NULL && second!=NULL) {
            ListNode* temp1 = first;
            ListNode* temp2 = second;
            if(second->next!=NULL)
                second = second->next->next;
            if(first->next!=NULL)
                first = first->next->next;
            p->next = temp2;
            p->next->next = temp1;
            p = p->next->next;
            p->next = NULL;
        }
        if(first!=NULL) {
            p->next = first;
        }
        return head->next;
    }
};

空间复杂度为O(1)





LeetCode答案源代码:https://github.com/SongLee24/LeetCode


posted @ 2015-05-24 08:55  神奕  阅读(130)  评论(0编辑  收藏  举报