• 【LeetCode】024. 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.

    题解:

      没什么好写的,链表题一般要注意头结点的问题,还有一定要画图!

    Solution 1

     1 /**
     2  * Definition for singly-linked list.
     3  * struct ListNode {
     4  *     int val;
     5  *     ListNode *next;
     6  *     ListNode(int x) : val(x), next(NULL) {}
     7  * };
     8  */
     9 class Solution {
    10 public:
    11     ListNode* swapPairs(ListNode* head) {
    12         ListNode dummy(-1);
    13         dummy.next = head;
    14         ListNode* cur = &dummy;
    15         
    16         while (cur->next && cur->next->next) {
    17             ListNode* tmp = cur->next->next;
    18             cur->next->next = tmp->next;
    19             tmp->next = cur->next;
    20             cur->next = tmp;
    21             cur = tmp->next;
    22         }
    23         
    24         return dummy.next;
    25     }
    26 };

      递归:

    Solution 2

     1 /**
     2  * Definition for singly-linked list.
     3  * struct ListNode {
     4  *     int val;
     5  *     ListNode *next;
     6  *     ListNode(int x) : val(x), next(NULL) {}
     7  * };
     8  */
     9 class Solution {
    10 public:
    11     ListNode* swapPairs(ListNode* head) {
    12         if (!head || !head->next)
    13             return head;
    14         ListNode* newHead = head->next;
    15         head->next = swapPairs(head->next->next);
    16         newHead->next = head;
    17         return newHead;
    18     }
    19 };
  • 相关阅读:
    Android的依赖注入框架:Dagger
    Android第三方开发组件
    Android 应用市场链接上传地址
    Android 开源框架以及开源项目以及连接
    Android 左右侧滑
    Android Textview 跑马灯
    Android XMPP推送
    Android多分辨率设配方案
    Android特效UI
    Android 时间的转换
  • 原文地址:https://www.cnblogs.com/Atanisi/p/8647298.html
Copyright © 2020-2023  润新知