LeetCode算法学习(10)

题目描述

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.

题目大意

对相邻的链表结点进行交换。

思路分析

链表题,关键在于处理好指针的变化;可以通过画图来找到思路。这题的关键在于交换完结点后的后续指针应该指向哪里。通过分析,可以得到两种情况:一种是后面还有不止两个结点,另一种是后面只有一个或零个结点。处理好这个关系就能很快的解决这道问题。

关键代码

    ListNode* swapPairs(ListNode* head) {
        bool flag = true;
        if (head == NULL) return head;
        ListNode *p = head, *q = head->next;
        if (p == NULL || q == NULL) return head;
        ListNode *result = head->next;
        ListNode *temp = q->next;
        while (p != NULL && q != NULL) {
            if (flag) {
                q->next = p;
                if (temp && temp->next)
                    p->next = temp->next;
                else
                    p->next = temp;
            } else {
                p = temp;
                if (p) q = p->next;
                if (q) temp = q->next;
            }
            flag = !flag;
        }
        return result;
    }

总结

链表复习2,需要冷静下来,画个图就出来的事情。

猜你喜欢

转载自blog.csdn.net/L_Realoo/article/details/85270706
今日推荐