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

    Swap Nodes in Pairs

    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.

    题中要求O(1)空间,且不允许修改list中节点的值。

    事实上我尝试修改节点的值,还是过了,哈哈

    算法思想:

    每次选两个节点,同时需要维护第三个指针,就是这两个节点的前驱,以防链表断链。两节点互换很容易,换完之后要与前驱节点链接。

    代码如下:

     1 public class Solution {
     2     public ListNode swapPairs(ListNode head) {
     3         if(head == null || head.next == null) return head;
     4         ListNode hhead = new ListNode(0);
     5         hhead.next = head;
     6         ListNode one = head;
     7         ListNode two = one.next;
     8         ListNode pre = hhead;
     9         while(one !=null && two != null){
    10             one.next = two.next;
    11             two.next = one;
    12             pre.next = two;
    13             pre = one;
    14             one = one.next;
    15             if(one == null) break;
    16             two = one.next;
    17         }
    18         return hhead.next;
    19     }
    20 }

    第二遍记录:

     1 public class Solution {
     2     public ListNode swapPairs(ListNode head) {
     3         if(head == null || head.next == null) return head;
     4         ListNode hhead = new ListNode(0);
     5         hhead.next = head;
     6         ListNode pre = hhead;
     7         while(pre.next != null && pre.next.next != null){
     8             ListNode p = pre.next.next;
     9             pre.next.next = p.next;
    10             p.next = pre.next;
    11             pre.next = p;
    12             pre = pre.next.next;
    13         }
    14         return hhead.next;
    15     }
    16 }

    两个指针就够用了,上一遍太小心了

  • 相关阅读:
    关于UITapGestureRecognizer的一些问题
    自定义导航栏返回按钮
    mousewheel滚轮事件 浏览器的写法
    Apache日志不记录图片文件设置方法和来源日志的配置
    redis持久化配置
    haproxy实现负载均衡
    Keepalived高可用软件的安装与配置
    Sublime text2用户自定义配置
    判断各版本的最简写法
    Ubuntu防火墙 UFW 设置
  • 原文地址:https://www.cnblogs.com/huntfor/p/3855170.html
Copyright © 2011-2022 走看看