转载

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;
    }
}
原文  https://segmentfault.com/a/1190000018116722
正文到此结束
Loading...