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

    标题: Swap Nodes in Pairs
    通过率: 32.5
    难度: 中等

    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-》2-》3-》4

    再操作3,4交换后要将2指向4,不能再指向3了,另外,再第一次交换的时候要把链表的入口换成2,具体细节操作见代码:

     1 /**
     2  * Definition for singly-linked list.
     3  * public class ListNode {
     4  *     int val;
     5  *     ListNode next;
     6  *     ListNode(int x) {
     7  *         val = x;
     8  *         next = null;
     9  *     }
    10  * }
    11  */
    12 public class Solution {
    13     public ListNode swapPairs(ListNode head) {
    14         if(head==null||head.next==null)return head;
    15         ListNode res=head;
    16         ListNode first=head,second=head.next,pre=null;
    17         int i=0;
    18         ListNode tmp=new ListNode(-1);
    19         while(second!=null){
    20             tmp.next=second.next;
    21             second.next=first;
    22             first.next=tmp.next;
    23             if(i==0)res=second;
    24             if(pre!=null)pre.next=second;
    25             pre=first;
    26             first=first.next;
    27             if(first==null)break;
    28             second=first.next;
    29             i=1;
    30             
    31         }
    32         return res;
    33     }
    34 }
  • 相关阅读:
    Cookie的定义和分类,及优缺点
    网页开发和设计
    电视精灵(新手练习项目)
    C#体检套餐项目
    C#简单的对象交互
    那些年我们学过的构造函数(构造方法,C#)
    员工打卡课后小项目
    SpringMVC类型转换器
    SpringMVC 异常处理3种方案
    SSH整合(一)hibernate+spring
  • 原文地址:https://www.cnblogs.com/pkuYang/p/4333918.html
Copyright © 2011-2022 走看看