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

    Given a linked list, swap every two adjacent nodes and return its head.

    Example:

    Given 1->2->3->4, you should return the list as 2->1->4->3.

    Note:

    • Your algorithm should use only constant extra space.
    • You may not modify the values in the list's nodes, only nodes itself may be changed.

    每次交换两个节点,用一个dummy node,放在head前,用以最后return head,需要两个指针,起始时p1 = dummy, p2 = head

    先记录一下p2.next.next的位置 (nextnode),此位置也是下一次swap的起点。p1指向p2.next,p2.next指向p2,p2指向nextnode。然后p1向前一步移动到p2位置,p2向前移动到nextnode的位置,直到 p1.next == null或者 p2.next = null,循环结束

    e.g.
    0 -> 1 -> 2 -> 3 -> 4 -> null      0->2, 2->1, 1->3 => 2->1->3->4->null
    p1                   n
      p2

    0 -> 2 -> 1 -> 3 -> 4 -> null      1->4, 4->3, 3->null => 1->4->3->null
          p1        n
           p2

    0 -> 2 -> 1 -> 4 -> 3 -> null      1->4, 4->3, 3->null => 1->4->3->null
               p1
                p2

    time: O(n), space: O(1)

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    class Solution {
        public ListNode swapPairs(ListNode head) {
            if(head == null || head.next == null) return head;
            ListNode dummy = new ListNode(0);
            dummy.next = head;
            ListNode p1 = dummy, p2 = head;
            while(p1.next != null && p2.next != null) {
                ListNode nextnode = p2.next.next;
                p1.next = p2.next;
                p2.next.next = p2;
                p2.next = nextnode;
    
                p1 = p2;
                p2 = nextnode;
            }
            return dummy.next;
        }
    }
  • 相关阅读:
    2017.10.25总结与回顾
    2017.10.24总结与回顾
    CSS盒子模型
    2017.10.23学习知识总结回顾及编写新网页
    JAVA与mysql之间的编码问题
    想写好代码,送你三个神器
    Vue+highligh.js实现语法高亮(转)
    Vue.JS实现复制到粘帖板功能
    npm install、npm install --save与npm install --save-dev区别(转)
    ES7与ES8新特性
  • 原文地址:https://www.cnblogs.com/fatttcat/p/10122632.html
Copyright © 2011-2022 走看看