zoukankan      html  css  js  c++  java
  • Leetcode 24. Swap Nodes in Pairs

    思路:添加头节点,依次反转相邻元素,保持反转后的最后一个指针pre,当前被反转的第一个元素的指针cur,当前被反转的第二个元素的指针next(如果存在的话)。反转的思路和92. Reverse Linked List II差不多,只不过pre要移动。

    迭代做法:

     1 /**
     2  * Definition for singly-linked list.
     3  * public class ListNode {
     4  *     int val;
     5  *     ListNode next;
     6  *     ListNode(int x) { val = x; }
     7  * }
     8  */
     9 class Solution {
    10     public ListNode swapPairs(ListNode head) {
    11         if(head == null) return head;
    12         ListNode dummy = new ListNode(0);
    13         dummy.next = head;
    14         ListNode pre = dummy, cur = head;
    15         while(cur != null && cur.next != null) {//保证有2个可以被反转的元素
    16             ListNode next = cur.next;
    17             cur.next = next.next;
    18             next.next = cur;
    19             pre.next = next;
    20             pre = cur;
    21             cur = cur.next;
    22         }
    23         return dummy.next;
    24     }
    25 }

    递归做法:

     1 /**
     2  * Definition for singly-linked list.
     3  * public class ListNode {
     4  *     int val;
     5  *     ListNode next;
     6  *     ListNode(int x) { val = x; }
     7  * }
     8  */
     9 class Solution {
    10     public ListNode swapPairs(ListNode head) {
    11         if(head == null || head.next == null) return head;//保证有2个可以被反转的元素
    12         ListNode cur = head, next = cur.next;
    13         cur.next = swapPairs(next.next);
    14         next.next = cur;
    15         return next;
    16     }
    17 }

    Next challenges: Reverse Nodes in k-Group

  • 相关阅读:
    基于Token的WEB后台认证机制
    导出和导入Docker容器
    进入Docker容器
    介绍Docker容器
    Docker镜像的实现原理
    Docker 移除镜像
    存出和载入Docker镜像
    Docker 创建镜像
    Docker 列出镜像
    Docker如何获取镜像
  • 原文地址:https://www.cnblogs.com/Deribs4/p/8414131.html
Copyright © 2011-2022 走看看