24. Swap Nodes in Pairs

发布时间:2019-06-07 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了24. Swap Nodes in Pairs脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

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

脚本宝典总结

以上是脚本宝典为你收集整理的24. Swap Nodes in Pairs全部内容,希望文章能够帮你解决24. Swap Nodes in Pairs所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: