美文网首页
【D11】两两交换链表中的节点&旋转链表(LC 24&61)

【D11】两两交换链表中的节点&旋转链表(LC 24&61)

作者: sirenyunpan | 来源:发表于2021-02-10 22:35 被阅读0次

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

问题描述

给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

解题思路

每次操作四个节点,分别是待交换的两个节点(head、pair)以及他们的前面一个节点(tempHead)和后面一个节点(tail)


交换节点操作

代码实现

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode swapPairs(ListNode head) {
        //链表中只有0个节点或1个节点时直接返回
        if(head == null || head.next == null){
            return head;
        }
        //添加虚拟头节点
        ListNode dumpyHead = new ListNode();
        dumpyHead.next = head;

        ListNode tempHead = dumpyHead;

        while(head != null && head.next != null){
            ListNode pair = head.next, tail = head.next.next;
            tempHead.next = pair;
            pair.next = head;
            head.next = tail;
            
            tempHead = head;
            head = tail;
        }
        return dumpyHead.next;
    }
}
  • 时间复杂度O(n)
  • 空间复杂度O(1)

61. 旋转链表

问题描述

给定一个链表,旋转链表,将链表每个节点向右移动 k 个位置,其中 k 是非负数。

解题思路

每次迭代相当于把链表最后一个节点挪动到链表头部,成为新的头节点。
解题关键:当链表的旋转次数等于链表长度时,链表会还原。因此需要取k整除链表长度的余数作为迭代次数。否则此种解法会超出时间限制。

代码实现

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode rotateRight(ListNode head, int k) {
        if(head == null || head.next == null){
            return head;
        }
        //旋转次数=链表长度时,链表会还原
        k = k % getLength(head);

        while(k != 0){
            ListNode temp = head;
            //找到倒数第二个节点
            while(temp.next.next != null){
              temp = temp.next;
            }
            ListNode tail = temp.next;
            tail.next = head;
            temp.next = null;
            head = tail;
            k = k-1;
        }
        return head;   
    }

    public int getLength(ListNode head){
        int len = 0;
        while(head != null){
            len++;
            head = head.next;
        }
        return len;
    }
}
  • 时间复杂度:最坏情况O(n^2),最好情况O(n)
  • 空间复杂度:最坏情况O(n),最好情况O(1)

相关文章

网友评论

      本文标题:【D11】两两交换链表中的节点&旋转链表(LC 24&61)

      本文链接:https://www.haomeiwen.com/subject/byflxltx.html