zoukankan      html  css  js  c++  java
  • 24. 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为例,为了方便计算首先添加一个头节点0,此时链表为0->1->2->3->4。题目要求两两节点相互交换,则最终的链表应该为0->2->1->4->3。

      首先关注节点1和2的交换。节点0为prev,节点1为cur,具体操作步骤为:

    • pre->next = cur->next;
    • cur->next = cur->next->next;
    • pre->next->next = cur;

      通过这样的操作后,此时链表为0->2->1->3->4。接下来是节点3和节点4的交换操作。具体步骤与节点1和节点2的交换步骤相一致,为了重复这一过程,需要更新prev和cur。具体操作步骤为:

    • pre = cur;
    • cur = cur->next;

    代码:

     1 class Solution {
     2 public:
     3     ListNode* swapPairs(ListNode* head) {
     4         if (head == NULL || head->next == NULL)
     5             return head;
     6         ListNode* newhead = new ListNode(0);
     7         newhead->next = head;
     8         ListNode* pre = newhead;
     9         ListNode* cur = head;
    10         while (cur && cur->next) {
    11             pre->next = cur->next;
    12             cur->next = cur->next->next;
    13             pre->next->next = cur;
    14             pre = cur;
    15             cur = cur->next;
    16         }
    17         return newhead->next;
    18     }
    19 };
  • 相关阅读:
    Struts的ONGL
    深度解析 Qt 中动态链接库
    QTcpSocket 发送数据的几种方法
    QT GUI总结
    Qt 插件学习(一)
    Qt自定义窗口部件
    Qt事件机制浅析
    VS2008 Qt Designer 中自定义信号槽
    Q窗口操作函数(窗口最大化,全屏,隐藏最大化最小化按钮)
    QT中窗口刷新事件的学习总结
  • 原文地址:https://www.cnblogs.com/sindy/p/6935185.html
Copyright © 2011-2022 走看看