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

    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.

    Subscribe to see which companies asked this question

     
     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) return head;
    12         ListNode res = new ListNode(0);
    13         ListNode pre = new ListNode(0);
    14         res.next = head;
    15         boolean isfirst = true;//标志是否第一次处理head,是的话将res指向第一个节点。
    16         while(head != null && head.next != null){
    17             pre.next = head.next;
    18             head.next = pre.next.next;
    19             pre.next.next = head;
    20             if(isfirst){
    21                 res.next = pre.next;
    22                 isfirst = false;
    23             }
    24             pre = pre.next.next;
    25             head = head.next;
    26         }
    27         return res.next;
    28     }
    29 }

    题目貌似要求不能改变节点的值,所以只能通过改变next 的指向来处理,只要在纸上画好链的拆解过程即可。

  • 相关阅读:
    样式
    样式表的类别、选择器和优先级
    随记
    框架
    表单元素
    HTLM内容容器标签和常用标签
    HTML5的意义、改变以及全局属性
    11月21日html基础
    感想 目标和展望
    C++结构体实例和类实例的初始化
  • 原文地址:https://www.cnblogs.com/guoguolan/p/5420625.html
Copyright © 2011-2022 走看看