leetcode 61题 旋转链表
给你一个链表的头节点 head ,旋转链表,将链表每个节点向右移动 k 个位置。
示例1
输入:head = [1,2,3,4,5], k = 2
输出:[4,5,1,2,3]
示例2
输入:head = [0,1,2], k = 4
输出:[2,0,1]
思路
通过求余的方式,确定最终反转的位置
代码
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @param {number} k
* @return {ListNode}
*/
function rotateRight(head, k) {
if (head === null || head.next === null || k === 0) {
return head;
}
let newHead = new ListNode(0);
newHead.next = head;
let len = 0;
let cur = newHead;
while (cur.next) {
len++;
cur = cur.next;
}
if (k % len === 0) {
return head;
}
cur.next = head;
cur = newHead;
for (let i=len-k%len; i>0; i--) {
cur = cur.next;
}
const res = new ListNode(0);
res.next = cur.next;
cur.next = null;
return res.next;
}
复杂度分析:
- 时间复杂度: O(N)
- 空间复杂度:O(N)
FEATURED TAGS
前端开发
H5
JavaScript
设计模式
browser
jQuery
源码分析
生活
leetcode
Array
Stack
Queue
Linked List
剑指offer
Binary Search Tree
Binary Tree
Breadth-First Search
Depth-First Search
String
Set
Binary Search
Sliding Window
Backtracking
Dynamic Programming
Two Pointers
Union Find
Sort
Bit Operation
Recursion
Map
Graph
Search
Hash
LinkedList
复盘
QuickSort
Trie
Design
MinHeap
Traverse
Min Heap
Node.js
BackEnd
SQL
MySQL
Design Patterns
Network
计算机网络
Python
SVG