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 }

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

  • 相关阅读:
    Linux之网络基础
    Tomcat配置虚拟目录并发布web应用
    Linux之权限管理操作
    Linux之shell编程基础
    Python简介
    Python代码注释 Python零基础入门教程
    Python Pycharm Anacanda 区别
    Python Hello World入门
    Python2.x 和 Python3.x,如何选择?
    数据库课程设计心得【1】
  • 原文地址:https://www.cnblogs.com/huntfor/p/3855170.html
Copyright © 2011-2022 走看看