• 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 }
  • 相关阅读:
    一个泛型的单例模式
    一个将Object转化为CSV文件的类
    WSDL.EXE Error: Not enough storage is avaliable to process the command.
    一个Linq Group By 和Sum的范例
    Random Cube Algorithm
    AccessImport demo
    .net controls of FileUpload
    asp.net AJAX
    Deploy iis7.5
    C# Fibonacci Sequence
  • 原文地址:https://www.cnblogs.com/ireneyanglan/p/4938928.html
Copyright © 2020-2023  润新知