zoukankan      html  css  js  c++  java
  • LeetCode 24. Swap Nodes in Pairs 成对交换节点 C++/Java

    Given a linked list, swap every two adjacent nodes and return its head.

    You may not modify the values in the list's nodes, only nodes itself may be changed.

    Example:

    Given 1->2->3->4, you should return the list as 2->1->4->3.

    奇数位和偶数位互换,若是奇数个,不用管最后一个

    解法一:(C++)

     1 ListNode* swapPairs(ListNode* head) {
     2         if(!head)
     3             return NULL;
     4         ListNode* dummy=new ListNode(-1),*cur=dummy;
     5         dummy->next=head;
     6         while(cur->next&&cur->next->next){
     7             ListNode* t=cur->next->next;
     8             cur->next->next=t->next;
     9             t->next=cur->next;
    10             cur->next=t;
    11             cur=t->next;
    12         }
    13         return dummy->next;
    14     }

    java:

     1 public ListNode swapPairs(ListNode head) {
     2         if(head==null)
     3             return null;
     4         ListNode dummy=new ListNode(-1),pre=dummy;
     5         dummy.next=head;
     6         while(pre.next!=null&&pre.next.next!=null){
     7             ListNode t=pre.next.next;
     8             pre.next.next=t.next;
     9             t.next=pre.next;
    10             pre.next=t;
    11             pre=t.next;
    12         }
    13         return dummy.next;
    14     }

    方法二:使用递归的方法,递归遍历到末尾两个,然后交换末尾两个,依次往前遍历(C++)

    1 ListNode* swapPairs(ListNode* head) {
    2         if(!head||!head->next)
    3             return head;
    4         ListNode* t=head->next;
    5         head->next=swapPairs(head->next->next);
    6         t->next=head;
    7         return t;
    8     }
  • 相关阅读:
    linux系统日志使用
    C# progressbar 用法
    python 新时代
    linux 常用命令 集锦
    c# DirectoryInfo类 详解
    哈佛(转)
    寒门难再出贵子
    排序算法
    JavaScript弹出框
    js中innerHTML与innerText的用法与区别
  • 原文地址:https://www.cnblogs.com/hhhhan1025/p/10639087.html
Copyright © 2011-2022 走看看