C++实现LeetCode(24.成对交换节点)

[LeetCode] 24. Swap Nodes in Pairs 成对交换节点

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.

这道题不算难,是基本的链表操作题,我们可以分别用递归和迭代来实现。对于迭代实现,还是需要建立 dummy 节点,注意在连接节点的时候,最好画个图,以免把自己搞晕了,参见代码如下:

解法一:

class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        ListNode *dummy = new ListNode(-1), *pre = dummy;
        dummy->next = head;
        while (pre->next && pre->next->next) {
            ListNode *t = pre->next->next;
            pre->next->next = t->next;
            t->next = pre->next;
            pre->next = t;
            pre = t->next;
        }
        return dummy->next;
    }
};

递归的写法就更简洁了,实际上利用了回溯的思想,递归遍历到链表末尾,然后先交换末尾两个,然后依次往前交换:

解法二:

class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        if (!head || !head->next) return head;
        ListNode *t = head->next;
        head->next = swapPairs(head->next->next);
        t->next = head;
        return t;
    }
};

解法三:

class Solution {
    public ListNode swapPairs(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode newHead = head.next;
        head.next = swapPairs(newHead.next);
        newHead.next = head;
        return newHead;
    }
}

到此这篇关于C++实现LeetCode(24.成对交换节点)的文章就介绍到这了,更多相关C++实现成对交换节点内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • C++实现LeetCode(18.四数之和)

    [LeetCode] 18. 4Sum 四数之和 Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target. Note: Elements in a quadruplet (a,b,c,d) must be

  • C++实现LeetCode(20.验证括号)

    [LeetCode] 20. Valid Parentheses 验证括号 Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string is valid if: Open brackets must be closed by the same type of brackets. Open

  • C++实现LeetCode(21.混合插入有序链表)

    [LeetCode] 21. Merge Two Sorted Lists 混合插入有序链表 Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists. Example: Input: 1->2->4, 1->3->4 Output: 1->1->2

  • C++实现LeetCode(26.有序数组中去除重复项)

    [LeetCode] 26. Remove Duplicates from Sorted Array 有序数组中去除重复项 Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length. Do not allocate extra space for another array, you must do this

  • C++实现LeetCode(19.移除链表倒数第N个节点)

    [LeetCode] 19. Remove Nth Node From End of List 移除链表倒数第N个节点 Given a linked list, remove the nth node from the end of list and return its head. For example, Given linked list: 1->2->3->4->5, and n = 2. After removing the second node from the en

  • C++实现LeetCode(25.每k个一组翻转链表)

    [LeetCode] 25. Reverse Nodes in k-Group 每k个一组翻转链表 Given a linked list, reverse the nodes of a linked list k at a time and return its modified list. k is a positive integer and is less than or equal to the length of the linked list. If the number of n

  • C++实现LeetCode(24.成对交换节点)

    [LeetCode] 24. Swap Nodes in Pairs 成对交换节点 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 t

  • 在CentOS 7上给一个网卡分配多个IP地址的方法

    有时你也许想要给一个网卡多个地址.你该怎么做呢?另外买一个网卡来分配地址?在小型网络中其实不用这么做.我们现在可以在CentOS/RHEL 7中给一个网卡分配多个ip地址.想知道怎么做么?好的,跟随我,这并不难. 首先,让我们找到网卡的IP地址.在我的CentOS 7服务器中,我只使用了一个网卡. 用root特权运行下面的命令: ip addr 示例输出: 1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN l

  • php将12小时制转换成24小时制的方法

    本文实例讲述了php将12小时制转换成24小时制的方法.分享给大家供大家参考.具体如下: php将12小时制转换成24小时制,输入格式为:02:30:00 pm 转换成:14:30:00 <?php function to_24_hour($hours,$minutes,$seconds,$meridiem){ $hours = sprintf('%02d',(int) $hours); $minutes = sprintf('%02d',(int) $minutes); $seconds =

  • C++实现LeetCode(13.罗马数字转化成整数)

    [LeetCode] 13. Roman to Integer 罗马数字转化成整数 Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. Symbol       Value I                  1 V                 5 X                10 L                 50 C                100 D 

  • C++实现LeetCode(12.整数转化成罗马数字)

    [LeetCode] 12. Integer to Roman 整数转化成罗马数字 Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M. Symbol       Value I                   1 V                  5 X                 10 L                  50 C                100

  • C++实现LeetCode(114.将二叉树展开成链表)

    [LeetCode] 114. Flatten Binary Tree to Linked List 将二叉树展开成链表 Given a binary tree, flatten it to a linked list in-place. For example, Given 1 / \ 2   5 / \   \ 3   4   6 The flattened tree should look like:    1 \ 2 \ 3 \ 4 \ 5 \ 6 click to show hints

  • 把jQuery的类、插件封装成seajs的模块的方法

    注:本文使用的seajs版本是2.1.1一.把Jquery封装成seajs的模块 复制代码 代码如下: define(function () { //这里放置jquery代码 把你喜欢的jquery版本放进来就好了 return $.noConflict();}); 调用方法:这样引进就可以像以前一样使用jquery 复制代码 代码如下: define(function (require, exports, module) {    var $ = require('./js/jquery');

  • php实现图片转换成ASCII码的方法

    本文实例讲述了php实现图片转换成ASCII码的方法.分享给大家供大家参考.具体如下: php图片转换成ASCII码,转换后可以直接通过字符串显示图片 <html> <head> <title>Ascii</title> <style> body{ line-height:0; font-size:1px; } </style> </head> <body> <?php $image = 'image.j

  • mysql时间戳转成常用可读时间格式的两种方法

    使用EXECL转换时间戳的公式为: 代码:=(xxxxxxxxxx+8*3600)/86400+70*365+19 使用MYSQL语句解释时间戳语法举例: 代码: SELECT FROM_UNIXTIME(1234567890, '%Y-%m-%d %H:%i:%S') 附:在mysql中,一个时间字段的存储类型是int(11),怎么转化成字符类型,比方存储为13270655222,需要转化为yyyy -mm-dd的形式 使用 FROM_UNIXTIME函数,具体如下: 代码:FROM_UNIX

  • js中的时间转换—毫秒转换成日期时间的示例代码

    js毫秒时间转换成日期时间 复制代码 代码如下: var oldTime = (new Date("2011/11/11 20:10:10")).getTime(); //得到毫秒数 大多数是用毫秒数除以365*24*60*60&1000,这么转回去,这种方法转换太过复杂,年月日,时分秒都要不同的方法获取,而且有的年份有366天,有的365天,这么算起来就太过复杂了. 后面自己试了一个方法,居然成功了 复制代码 代码如下: var oldTime = (new Date(&qu

随机推荐