24. Swap Nodes in Pairs

栏目: 数据库 · 发布时间: 5年前

内容简介: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 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.

难度: medium

题目:

给定链表,交换相邻的两个结点并返回其头结点。

不可以修改结点的值,只可以改变结点本身。

思路:加个头结点简化操作。然后就是简单的链表置换。

Runtime: 2 ms, faster than 99.98% of Java online submissions for Swap Nodes in Pairs.

Memory Usage: 26 MB, less than 6.66% of Java online submissions for Swap Nodes in Pairs.

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode swapPairs(ListNode head) {
        ListNode dummyHead = new ListNode(0);
        dummyHead.next = head;
        ListNode prev = dummyHead;
        ListNode next = prev.next;
        while (next != null) {
            ListNode nextNext = next.next;
            if (nextNext != null) {
                prev.next = nextNext;
                next.next = nextNext.next;
                nextNext.next = next;
            }
            prev = next;
            next = prev.next;
        }
        
        return dummyHead.next;
    }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

天涯虚拟社区

天涯虚拟社区

刘华芹 / 民族出版社 / 2005-11 / 23.00元

网络空间很复杂,好多人并不完全了解或者只是了解到一些皮毛。比如说好多人对于见网友一事总是抱着浪漫或者暖昧的想法,而事实却并不总是想象的那样。作者在做虚拟社区研究甚至是在有这个想法之前并不常呆在网上,互联网对于作者来说就是查查资料、收发信年、看看新闻的工具。担是看着越来越多的人把时间花在网上,一处文化上的直觉告诉作者:有一种新的生活方式产生了。强烈的好奇心驱使着作者走到了网上,走到了天涯虚拟社区,并......一起来看看 《天涯虚拟社区》 这本书的介绍吧!

MD5 加密
MD5 加密

MD5 加密工具

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具