zoukankan      html  css  js  c++  java
  • LeetCode(24): 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.

    题意:交换一个链表中相邻的两个元素,不能只交换结点元素值,要进行结点的操作。

    思路:使用3个指针,分别记录当前指针,当前指针的前驱,当前指针的后继,然后进行交换操作。

    代码:

    public ListNode swapPairs(ListNode head) {
              if(head==null) return head;
              ListNode pPrePre = null;
              ListNode pPre = null;
              ListNode p = head;
              while(p!=null&&p.next!=null){
                  pPre = p;
                  p = p.next;
                  ListNode pNext = p.next;
                  if(pPre==head) head=p;
                  if(pPrePre!=null) pPrePre.next = p;
                  p.next = pPre;
                  pPre.next = pNext;
                  pPrePre = pPre;
                  p=pNext;
              }
              return head;
        }
  • 相关阅读:
    【Liunx】centos防火墙
    【Liunx】基础命令
    【Flask】CBV模式
    【Flask】第三方插件
    【Flask】登录练习
    【Flask】特殊装饰器
    【Flask】蓝图
    Django之视图层
    Django之路由控制配置
    Django之静态文件配置
  • 原文地址:https://www.cnblogs.com/Lewisr/p/5134482.html
Copyright © 2011-2022 走看看