61.旋转链表

时游小于 1 分钟LeetCode

61.旋转链表

/*
 * @lc app=leetcode.cn id=61 lang=typescript
 *
 * [61] 旋转链表
 */

// @lc code=start
/**
 * Definition for singly-linked list.
 * class ListNode {
 *     val: number
 *     next: ListNode | null
 *     constructor(val?: number, next?: ListNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.next = (next===undefined ? null : next)
 *     }
 * }
 */

function rotateRight(head: ListNode | null, k: number): ListNode | null {
	if (head == null) return null;
	let newNode = new ListNode(0, head);
	// 获取长度
	let len = 1;
	let current = head;
	while (current.next) {
		current = current.next;
		len++;
	}
	k = k % len;
	for (let i = 0; i < k; i++) {
		// pre、end
		let start = newNode.next;
		let pre: ListNode = head;
		let end: ListNode = head;
		let index = 0;
		let currentNode = newNode.next as ListNode;
		while (index < len) {
			if (index == len - 1) {
				// 末尾项
				end = currentNode;
			}
			if (index == len - 2) {
				// 末尾前一项
				pre = currentNode;
			}

			currentNode = currentNode.next as ListNode;
			index++;
		}
		end.next = start;
		pre.next = null;
		newNode.next = end;
	}
	return newNode.next;
}

class ListNode {
	val: number;
	next: ListNode | null;
	constructor(val?: number, next?: ListNode | null) {
		this.val = val === undefined ? 0 : val;
		this.next = next === undefined ? null : next;
	}
}

let listTag1 = new ListNode(1);
let listTag2 = new ListNode(2);
let listTag3 = new ListNode(3);

listTag1.next = listTag2;
listTag2.next = listTag3;

console.log(rotateRight(listTag1, 2000000000));
// @lc code=end

上次编辑于:
贡献者: 15327360835
Loading...