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 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:Github精选:本周10大热门项目
下一篇:LeetCode实战:合并两个有序链表

发表评论

最新留言

网站不错 人气很旺了 加油
[***.192.178.218]2024年04月12日 01时35分55秒