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

    Question

    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.

    Solution

    这题的核心在于dummy node和list操作。

    dummy -> 1 -> 2 -> 3 -> 4

    prev   cur   next  tmp

    我们用四个指针来完成操作。

    1. 预存tmp: tmp = next.next

    2. 更改next: next.next = cur

    3. 更改cur: cur.next = tmp

    4. 更改prev: prev.next = next

    5. 更新prev, cur, next:

    cur = tmp

    if (cur != null): next = cur.next

    prev = prev.next.next

    最后返回dummy.next

    我们看到循环结束的条件应该是tmp为null或者tmp.next为null.

     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 dummy = new ListNode(-1);
    15         dummy.next = head;
    16         ListNode prev = dummy, current = head, next = head.next, tmp;
    17         while (next != null) {
    18             tmp = next.next;
    19             next.next = current;
    20             current.next = tmp;
    21             prev.next = next;
    22             current = tmp;
    23             prev = prev.next.next;
    24             if (current == null) {
    25                 break;
    26             } else {
    27                 next = current.next;
    28             }
    29         }
    30         return dummy.next;
    31     }
    32 }
  • 相关阅读:
    [Java Spring] Convertors
    [Java Spring] @InitBinder
    [Java Spring] Validations for Entity
    [Java JPA] @Query
    测试人员为什么要深入到项目实现中去
    有赞的深度需求功能测试
    youtube-dl 使用
    mysql update 的时候使用left join和where语句
    openstack 虚拟机设备管理器cpu核数与任务管理器不一致
    tcp扫描器实现原理
  • 原文地址:https://www.cnblogs.com/ireneyanglan/p/4938928.html
Copyright © 2011-2022 走看看