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

    双指针互换,要考虑一些边界条件,比如链表为空,链表长度为1,链表长度为2.
    加一个safeGuard可以避开链表长度为2的检测。

     1 /**
     2  * Definition for singly-linked list.
     3  * public class ListNode {
     4  *     int val;
     5  *     ListNode next;
     6  *     ListNode(int x) {
     7  *         val = x;
     8  *         next = null;
     9  *     }
    10  * }
    11  */
    12 public class Solution {
    13     public ListNode swapPairs(ListNode head) {
    14         // Start typing your Java solution below
    15         // DO NOT write main() function
    16         
    17         if(head == null)
    18             return null;
    19             
    20         ListNode safeG = new ListNode(-1);
    21         safeG.next = head;
    22         ListNode before = safeG;
    23         ListNode cur = safeG.next;
    24         ListNode after = cur.next;
    25         
    26         while(after != null){
    27             ListNode tmp = after.next;
    28             after.next = cur;
    29             cur.next = tmp;
    30             before.next = after;
    31             before = cur;
    32             if(before.next == null)
    33                 break;
    34                 
    35             cur = before.next;
    36             after = cur.next;
    37         }
    38         
    39         head = safeG.next;
    40         return head;
    41         
    42     }
    43 }
  • 相关阅读:
    Go 单元测试、基准测试、并发基准测试
    Go url编码和字符转码
    ssh 登录进入 docker container
    Python 开发
    Ethereum 源码分析之 accounts
    Ethereum 源码分析之框架
    数据库视图
    共识算法:PBFT、RAFT
    JQuery Mobile
    Android Studio
  • 原文地址:https://www.cnblogs.com/feiling/p/3199460.html
Copyright © 2011-2022 走看看