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

     

  • 相关阅读:
    浅谈 LCA
    树剖毒瘤题整理
    树链剖分&咕咕咕了好久好久的qtree3
    洛谷P4095新背包问题
    洛谷P4127同类分布
    洛谷P4124 手机号码
    数位dp好题整理+自己wa过的细节记录
    P4999烦(gui)人(chu)的数学作业
    洛谷P4317 花(fa)神的数论题(数位dp解法)
    网络流之最短路径覆盖问题
  • 原文地址:https://www.cnblogs.com/fenshen371/p/4906081.html
Copyright © 2011-2022 走看看