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

    题目要求成对翻转指针,难度一般,要求使用常数的空间,应当使用迭代的方法而非递归的方法,这里我们加上一个头结点dummy,这样一来即使翻转的节点涉及到头结点,需要修改头指针,我们也可以做到和一般节点一样处理,我们设置了一个指针pre指向“一对”节点,一个指针t指向一对节点的第二个节点

    【图解稍后补充】

    代码如下:

     1 /**
     2  * Definition for singly-linked list.
     3  * struct ListNode {
     4  *     int val;
     5  *     ListNode *next;
     6  *     ListNode(int x) : val(x), next(NULL) {}
     7  * };
     8  */
     9 class Solution {
    10 public:
    11     ListNode* swapPairs(ListNode* head) {
    12         ListNode *dummy = new ListNode(-1), *pre = dummy;
    13         dummy->next = head;
    14         while (pre->next && pre->next->next)
    15         {
    16             ListNode *t = pre->next->next;
    17             pre->next->next = t->next;
    18             t->next = pre->next;
    19             pre->next = t;
    20             pre = t->next;
    21         }
    22         return dummy->next;
    23     }
    24 };
  • 相关阅读:
    Vue项目端口号占用
    理解vuex -- vue的状态管理模式
    2018-7-10杂记
    JS 数组操作总结
    JS 字符串操作总结
    【javascript练习题】函数
    【javascript练习题】this指针和作用域
    canal实时同步mysql binlog到rabbitmq
    Hexo+GitHub+Netlify一站式搭建属于自己的博客网站
    Git学习原版手稿
  • 原文地址:https://www.cnblogs.com/dapeng-bupt/p/8169113.html
Copyright © 2011-2022 走看看