Leetcode - java - 24. 两两交换链表中的节点

题目

给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。

示例:

给定 1->2->3->4, 你应该返回 2->1->4->3.
说明:

你的算法只能使用常数的额外空间。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

解题

(1)、用时 4ms

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode swapPairs(ListNode head) {
        if(head == null || head.next == null){
            return head;
        }
        ListNode prev = new ListNode(0);
        prev.next = head;
        ListNode self = head.next;
        while(prev.next !=null && prev.next.next != null){
            ListNode a = prev.next;
            ListNode b = a.next;
            //交换位置
            prev.next = b;
            a.next = b.next;
            b.next = a;
            //下移
            prev = a;
        }
        
        return self;
    }
}

在这里插入图片描述

(2)、执行用时为 2 ms 的范例

class Solution {
    public ListNode swapPairs(ListNode head) {
        if(head == null||head.next == null)
            return head;
        ListNode pre = head;
        ListNode temp = pre.next;
        ListNode resHead = temp;
        ListNode link = head;
        while(temp!=null){
            pre.next = temp.next;
            temp.next = pre;
            pre = pre.next;
            if(pre == null){
                break;
            }
            temp = pre.next;
            if(temp!=null){
                link.next = temp;
                link = pre;
            }else{
                link.next = pre;
                break;
            }
            
        }
        return resHead;
    }
}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/wangnanwlw/article/details/86522384