LeetCode 24 Swap Nodes in Pairs(交换序列中的结点)

简介:

翻译

给定一个链表,调换每两个相邻节点,并返回其头部。

例如,
给定 1->2->3->4, 你应该返回的链表是 2->1->4->3。

你的算法必须使用唯一不变的空间。

你也不能修改列表中的值,只有节点本身是可以改变的。

原文

Give 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,2,3,4作为示例,将其作为两部分

1,2 -- 3,4

或者我画个图出来更加直观吧……

这里写图片描述

代码

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *    int val;
 *    ListNode* next;
 *    ListNode(int x): val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        if(head == NULL) return NULL;
        if(head->next == NULL) return head;

        ListNode* temp = head->next;
        head->next = swapPairs(temp->next);
        temp->next = head;

        return temp;
    }
};
目录
相关文章
|
1月前
|
存储 算法
《LeetCode》—— 摆动序列
《LeetCode》—— 摆动序列
|
1月前
|
算法
LeetCode刷题---19. 删除链表的倒数第 N 个结点(双指针-快慢指针)
LeetCode刷题---19. 删除链表的倒数第 N 个结点(双指针-快慢指针)
|
1月前
|
测试技术
力扣888 公平糖果交换
力扣888 公平糖果交换
|
1月前
|
算法 安全 数据处理
LeetCode刷题---707. 设计链表(双向链表-带头尾双结点)
LeetCode刷题---707. 设计链表(双向链表-带头尾双结点)
|
3月前
|
算法 安全 测试技术
[组合数学]LeetCode:2954:统计感冒序列的数目
[组合数学]LeetCode:2954:统计感冒序列的数目
|
3月前
|
算法 测试技术 C#
【单调栈】LeetCode2030:含特定字母的最小子序列
【单调栈】LeetCode2030:含特定字母的最小子序列
LeetCode | 19. 删除链表的倒数第 N 个结点
LeetCode | 19. 删除链表的倒数第 N 个结点
|
1月前
LeetCode刷题---876. 链表的中间结点(快慢指针)
LeetCode刷题---876. 链表的中间结点(快慢指针)
|
1月前
|
存储
力扣187 重复DNA序列
力扣187 重复DNA序列
|
1月前
|
C语言
反转链表、链表的中间结点、合并两个有序链表【LeetCode刷题日志】
反转链表、链表的中间结点、合并两个有序链表【LeetCode刷题日志】