LeetCode实战:两两交换链表中的节点
发布日期:2021-06-30 22:56:56
浏览次数:2
分类:技术文章
本文共 1201 字,大约阅读时间需要 4 分钟。
题目英文
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.
题目中文
给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
示例:
给定 1->2->3->4, 你应该返回 2->1->4->3.
算法实现
/** * Definition for singly-linked list. * public class ListNode { * public int val; * public ListNode next; * public ListNode(int x) { val = x; } * } */ public class Solution{ public ListNode SwapPairs(ListNode head) { if (head == null || head.next == null) return head; head = Swap(head); ListNode temp = head.next; while (temp != null && temp.next != null) { temp.next = Swap(temp.next); if (temp.next != null) { temp = temp.next.next; } } return head; } public ListNode Swap(ListNode node) { if (node == null || node.next == null) return node; ListNode t = node.next; node.next = t.next; t.next = node; return t; }}
实验结果
相关图文:
转载地址:https://lsgogroup.blog.csdn.net/article/details/89372408 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
网站不错 人气很旺了 加油
[***.192.178.218]2024年04月12日 01时35分55秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
Python解惑之:True与False
2019-05-01
你要的微信小程序终于来了
2019-05-01
我的2016书单
2019-05-01
冷眼看小程序
2019-05-01
为什么执行 x in range(y) 如此快?
2019-05-01
看完这篇文章你还不理解 Python 装饰器,只有一种可能...
2019-05-01
Python干货:表达式 i += x 与 i = i + x 等价吗?
2019-05-01
有了这些 Chrome 插件,效率提升10倍(建议收藏)
2019-05-01
Python 编码错误的本质原因
2019-05-01
Python 开发者都会遇到的错误:UnboundLocalError
2019-05-01
用 Python 送“爱心”
2019-05-01
理解HTTPS为什么安全前,先看看这些东西
2019-05-01
最通俗易懂地解释:正向代理与反向代理
2019-05-01
代码这样写不止于优雅(Python版)
2019-05-01
一份来自掘金社区的开发者报告
2019-05-01
Python是怎么火起来的
2019-05-01
一本书搞定Python入门到实践
2019-05-01
20-40k+期权,蚂蚁金服招 Python 开发工程师
2019-05-01
2017半年文章合集(建议收藏)
2019-05-01
简析 __init__、__new__、__call__ 方法
2019-05-01