zoukankan      html  css  js  c++  java
  • LeetCode Swap Nodes in Pairs

    原题链接在这里:https://leetcode.com/problems/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. 

    题解:

    需要建一个dunmy,最后return dunmy.next. 如此可以避免边界问题的讨论,例如头两个点的转换。

    Time Complexity: O(n), n是list的长度. Space: O(1).

    AC Java:

     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 public class Solution {
    10     public ListNode swapPairs(ListNode head) {
    11         if(head == null || head.next == null){
    12             return head;
    13         }
    14         
    15         ListNode dummy = new ListNode(0);
    16         dummy.next = head;
    17         
    18         ListNode mark = dummy;
    19         ListNode A;
    20         ListNode B;
    21         while(mark.next != null && mark.next.next != null){
    22             A = mark.next;
    23             B = mark.next.next;
    24             A.next = B.next;
    25             B.next = A;
    26             mark.next = B;
    27             mark = mark.next.next;
    28         }
    29         return dummy.next;
    30     }
    31 }

    Recursion解法.

    Time Complexity: O(n). Space: O(n), stack space.

    AC Java: 

     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 public class Solution {
    10     public ListNode swapPairs(ListNode head) {
    11         if(head == null || head.next == null){
    12             return head;
    13         }
    14         ListNode n = head.next;
    15         head.next = swapPairs(n.next);
    16         n.next = head;
    17         return n;
    18     }
    19 }

    跟上Reverse Nodes in k-Group.

  • 相关阅读:
    清北刷题班day3 morning
    [NOI1997] 积木游戏(dp)
    [NOI1999] 棋盘分割(推式子+dp)
    2017北京国庆刷题Day7 afternoon
    湖南集训day8
    湖南集训day7
    湖南集训day6
    湖南集训day5
    湖南集训day4
    湖南集训day3
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/4825008.html
Copyright © 2011-2022 走看看