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

    https://leetcode.com/problems/swap-nodes-in-pairs/description/
    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.
     1 public ListNode swapPairs(ListNode head) {
     2         //如果是最后一对的话,head.next.next 是可以为 NULL 的,所以不要进行判断
     3         if (head == null || head.next == null) return head;
     4         //base
     5         ListNode newHead = swapPairs(head.next.next) ;//head is 1, newHead is 4
     6         //currently head is 1,   4->3->null
     7         ListNode tail = head.next ; //tail is 2
     8         head.next = newHead ; //1->4
     9         tail.next = head ; //2->1
    10         return tail;
    11     }

    2-1-4-3-5

    5 自己就弹了,所以没有后面的处理,所以(head=3)head.next 还是 直接连 last pop newhead(5) 所以是 2-1-4-3-5

    要深刻理解当时stack 里 head = 3 newhead=5 这一点!

  • 相关阅读:
    StackView
    横竖屏
    Html
    UILabel
    NSString
    NSPredicate|谓词
    iphone
    函数
    UIBezierPath
    UICollectionView
  • 原文地址:https://www.cnblogs.com/davidnyc/p/8456484.html
Copyright © 2011-2022 走看看