分享

LeetCode实战:两两交换链表中的节点

 老马的程序人生 2020-08-17

题目英文

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;
    }
}

实验结果

提交记录

相关图文


经过8年多的发展,LSGO软件技术团队在「地理信息系统」、「数据统计分析」、「计算机视觉」等领域积累了丰富的研发经验,也建立了人才培养的完备体系,欢迎对计算机技术感兴趣的同学加入,与我们共同成长进步。

我们图文推送的计划如下,欢迎大家转发!

  • 周一「图书排行:计算机书籍每周销量排行榜」

  • 周二「技术分享:C#语言在工程中的应用」

  • 周三「资料分享:网络上发现的电子资料」

  • 周四「LeetCode实战:算法题目的实现

  • 周五「猫眼电影:即将上映、最受期待榜」

  • 周六「Github精选:本周10大热门项目」

  • 周日「股市币市:本周交易数据分析与最新公告」

    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多