zoukankan      html  css  js  c++  java
  • 【LeetCode练习题】Swap Nodes in Pairs

    Swap Nodes in Pairs

    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.

    相邻两个节点为一组,交换一组内节点的位置,如1和2交换,3和4交换。

    不能改变节点里values的值,而且只能使用常量的空间。

    解题思路:

    • 设置一个dummy头节点方便对第一个节点进行操作。
    • 然后有三个指针 pre,first,second。 first和second分别指向待交换的第一个和第二个节点,pre指针指向first之前的那个节点。
    • 交换first和second指针的节点,交换过程如图:

    • 交换后,判断first节点后面有没有节点了,有一个还是有两个节点。
    • 如果后面有一个节点或者没有节点,链表交换完毕,退出循环。
    • 如果后面有两个节点,first后移,设置pre和second的新位置,再次执行上面的交换操作。
    • 循环退出后,链表已经交换了顺序了。
    • 删除dummy节点,返回head指针。

    代码如下:

    class Solution {
    public:
        ListNode *swapPairs(ListNode *head) {
            if(head == NULL)
                return NULL;
            ListNode *dummy = new ListNode(0);
            dummy->next = head;
            ListNode *pre = dummy,*first = head,*second = head->next;
            
            if(second == NULL){
                //只有一个节点
                delete dummy;
                return head;
            }
            else{
                //先交换第一个和第二个节点
                pre->next = second;
                first->next = second->next;
                second->next = first;
            }
    
            while(true){
                if(first->next == NULL || first->next->next == NULL)
                    //first后面没有节点或者只有一个节点
                    break;
                else{
                    //有两个节点
                    pre = first;
                    first = first->next;
                    second = first->next;
    
                    pre->next = second;
                    first->next = second->next;
                    second->next = first;
                }
            }
            head = dummy->next;
            delete dummy;
            return head;
        }
    };
  • 相关阅读:
    关于数组的tip
    php 计算注册的天数
    PHP推送接口
    nginx 301 重定向
    tp3、tp5 输出上一次sql语句
    MySQL not null 取消条件限制
    vscode查看PHP函数来源
    关于git及项目的归档
    我的第一个JW项目——网上商城设计说明书(六)
    我的第一个JW项目——网上商城设计说明书(五)
  • 原文地址:https://www.cnblogs.com/4everlove/p/3660639.html
Copyright © 2011-2022 走看看