LeetCode 24. Swap Nodes in Pairs(链表交换操作)

LeetCode 24. Swap Nodes in Pairs


题目描述:

Given a linked list, swap every two adjacent nodes and return its head.

Example:

Given 1->2->3->4, you should return the list as 2->1->4->3.

Note:

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

题目理解:

给定一个链表,每两个元素交换一次,最后返回链表的头元素。
要求:算法只能使用常数级别的空间,不能改变链表结点的值,只能通过交换结点的方式调换顺序。

思路:很直观的思路,每两个结点交换一次,因为使用的结构体指针,所以没法进行结点之间的直接交换,必须通过修改next来修改链表的顺序。提交了过后,发现里面有使用0ms解决问题,而我的算法是属于递归调用时间数量级的,需要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) {
        ListNode* first = head;
        if(!first) return NULL;
        ListNode* second = head->next;
        if(!second) return head;

        ListNode* tmp2 = new ListNode(0);
        ListNode* pre = new ListNode(0);
        tmp2 = second->next;
        second->next = first;
        first->next = tmp2;
        head = second;
        pre = first;

        first = first-> next;
        if(!first) return head; 
        second = first-> next;
        while(second!=NULL){
            ListNode* tmp = new ListNode(0);

            tmp = second->next;
            second->next = first;
            first->next = tmp;
            pre->next = second;
            pre = first;

            first = first-> next;
            if(!first) break; 
            second = first-> next;
        }
        return head;
    }
};

这是精简后的:

class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        ListNode* first = head;
        if(!first) return NULL;
        ListNode* second = head->next;
        if(!second) return head;
        ListNode* start = new ListNode(0);
        start->next = head;
        ListNode* pre = start;
        while(second!=NULL){
            ListNode* tmp = second->next;
            second->next = first;
            first->next = tmp;
            pre->next = second;
            pre = first;
            first = first-> next;
            if(!first) break; 
            second = first-> next;
        }
        return start->next;
    }
};

其实就是多生成了一个头结点,让之前第一次的交换也有了规律,当时觉得别扭却怎么也想不到方法整合,还是思维太懒惰了。


这是优秀代码中的递归思想解法:

class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        if (head==NULL) return NULL;
        if (head->next==NULL) return head;
        ListNode *tmp=swapPairs(head->next->next);
        ListNode *p=head->next;
        p->next = head;
        head->next = tmp;
        return p;
    }
};

至于时间复杂度为什么会跟递归一样。具体也没搞明白。。。

猜你喜欢

转载自blog.csdn.net/qq_40280096/article/details/81874235