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 };

     

  • 相关阅读:
    hive中如何查询除了其中某个字段剩余所有字段
    查找出不同环境下同一张表的数据差异
    pycharm中导入包失败的解决办法
    hive如何获取当前时间
    python-匿名函数
    Tensorflow报错:OMP: Error #15: Initializing libiomp5.dylib, but found libiomp5.dylib already initialized.
    Tensorflow中Tensor对象的常用方法(持续更新)
    Numpy中的广播机制,数组的广播机制(Broadcasting)
    重装conda
    matplotlib作图一例
  • 原文地址:https://www.cnblogs.com/fenshen371/p/4906081.html
Copyright © 2011-2022 走看看