zoukankan      html  css  js  c++  java
  • 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.

     

    思路:设置两个指针,slow和fast。

    先考虑链表中的头两个节点,使slow等于head,而fast等于第二个节点。

    转换操作为

    1 slow->next = fast->next;
    2 fast->next = slow;

    之后考虑后面节点的情况。

    假设有链表1->2->3->4->5->6。

    现在我们要交换3和4。则使slow指向要交换的两个节点的前一个节点,这里是2;使fast指向要交换的两个节点中的后一个,这里是4。

    转换操作为

    1 slow->next->next = fast->next;
    2 fast->next = slow->next;
    3 slow->next = fast;

    swap操作我们在while循环中进行,因此交换完之后,我们要让slow指针指向已交换完的两个节点中的后一个,让fast指向下一组要交换节点中的后一个。

    其中,在给fast赋值时要检测是否链表已经到头了,如果到头了后面就没有要交换的节点了。

    赋值操作如下

    1 slow = slow->next->next;
    2 if (slow->next != NULL && slow->next->next != NULL)
    3     fast = slow->next->next;
    4 else break;

     

    完整代码如下

     1 class Solution {
     2 public:
     3     ListNode* swapPairs(ListNode* head) {
     4         if (head == NULL || head->next == NULL)
     5             return head;
     6         ListNode* res = NULL;
     7         ListNode* slow = head;
     8         ListNode* fast = slow->next;
     9         while (1)
    10         {
    11             if (res == NULL)
    12             {
    13                 res = fast;
    14                 slow->next = fast->next;
    15                 fast->next = slow;
    16                 if (slow->next != NULL && slow->next->next != NULL)
    17                     fast = slow->next->next;
    18                 else break;
    19             }
    20             slow->next->next = fast->next;
    21             fast->next = slow->next;
    22             slow->next = fast;
    23             slow = slow->next->next;
    24             if (slow->next != NULL && slow->next->next != NULL)
    25                 fast = slow->next->next;
    26             else break;
    27         }
    28         return res;
    29     }
    30 };

     

  • 相关阅读:
    类 2020年8月19
    随便一写,明天改正
    os模块 2020年8月16
    time 模块 2020年8月16
    collections模块 2020年8月16
    正则跟re模块内容2020年8月16日
    【C++设计模式二】C++工厂模式
    【C++设计模式一】C++简单工厂模式
    【01-springmvc快速入门、组件解析】
    03-【Spring 的 AOP】
  • 原文地址:https://www.cnblogs.com/fenshen371/p/4906081.html
Copyright © 2011-2022 走看看