zoukankan      html  css  js  c++  java
  • [Leetcode]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 class Solution {
     2 public:
     3     ListNode *swapPairs(ListNode *head) {
     4         if(head==NULL || head->next==NULL)
     5             return head;
     6         ListNode *temp = head->next;
     7         ListNode *forward = temp->next;
     8         head->next->next = head;
     9         head->next=swapPairs(forward);
    10         return temp;
    11     }
    12 };
  • 相关阅读:
    CISCO一些基本配置
    每日学习
    每日学习(个人作业2)
    每日学习
    团队冲刺第十四天
    每日学习
    团队冲刺第十三天
    每日学习
    团队冲刺第十二天
    2021.5.26
  • 原文地址:https://www.cnblogs.com/desp/p/4345793.html
Copyright © 2011-2022 走看看