zoukankan      html  css  js  c++  java
  • 【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 };
  • 相关阅读:
    python random模块随机取list中的某个值
    初学习-python打印乘法表、正方形、三角形
    python字符串拼接相关
    导航条2-
    HTML输入验证提示信息
    CMD常用功能
    AngularJs学习笔记(4)——自定义指令
    AngularJs学习笔记(3)——scope
    AngularJs学习笔记(2)——ng-include
    AngularJs学习笔记(1)——ng-app
  • 原文地址:https://www.cnblogs.com/Atanisi/p/8647298.html
Copyright © 2011-2022 走看看