• 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.

    第一遍:

     1 public class Solution {
     2     public ListNode swapPairs(ListNode head) {
     3         // Note: The Solution object is instantiated only once and is reused by each test case.
     4         if(head == null || head.next == null) return head;
     5         ListNode header = new ListNode(-1), first = head, second = head.next, cur = header;
     6         header. next = head;
     7         while(second != null){
     8             first.next = second.next;
     9             second.next = first;
    10             cur.next = second;
    11             cur = first;
    12             first = cur.next;
    13             if(first != null)
    14                 second = first.next;
    15             else
    16                 second = null;
    17         }
    18         return header.next;
    19     }
    20 }

    第三遍:

     1 public class Solution {
     2     public ListNode swapPairs(ListNode head) {
     3         ListNode header = new ListNode(-1);
     4         header.next = head;
     5         ListNode cur = header;
     6         while(cur.next != null && cur.next.next != null){
     7             ListNode first = cur.next.next, second = cur.next;
     8             second.next = first.next;
     9             cur.next = first;
    10             first.next = second;
    11             cur = second;
    12         }
    13         return header.next;
    14     }
    15 }
  • 相关阅读:
    数据库模糊查询
    Redis集群简介
    POI导出Excel的三种 workbook的区别
    mysql主从跳过错误
    MySQL server has gone away 问题解决方法
    Redis批量删除key的命令
    Python 3.6学习笔记(一)
    maven项目报错
    使用zabbix监控mysql的三种方式
    postgresql初体验
  • 原文地址:https://www.cnblogs.com/reynold-lei/p/3896270.html
Copyright © 2020-2023  润新知