LeetCode 24.两两交换链表中的节点

题目传送门:两两交换链表中的节点


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

你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。


示例:

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

递归法:

  • 时间复杂度:O(N),其中 N 指的是链表的节点数量。
  • 空间复杂度:O(N),递归过程使用的堆栈空间。
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode swapPairs(ListNode head) {
        //1.如果链表的长度小于2,则没有可交换的元素,返回链表
        if(head == null || head.next == null) return head;
        ListNode next = head.next;
        //2.使用递归的方法解决问题,因为是两两交换节点,所以参数为next.next
        head.next = swapPairs(next.next);
        //3.解决简单问题
        next.next=head;
        return next;
    }
}

迭代法:

  • 时间复杂度:O(N),其中 N 指的是链表的节点数量。
  • 空间复杂度:O(1)。
/**
 * 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 dummy = new ListNode(-1);
        dummy.next = head;
        ListNode pre = dummy;

        while((head != null)&&(head.next != null)) {
            //1.首先定义两个点的位置
            ListNode first = head;
            ListNode second = head.next;

            //进行交换操作
            pre.next = second;
            first.next = second.next;
            second.next = first;

            //进行指针的移动
            pre = first;
            head = first.next;
        }
        return dummy.next;
    }
}
posted @ 2020-08-24 18:19  南笙北沫  阅读(125)  评论(0编辑  收藏  举报