当前位置:网站首页>Force button brushing question 61. rotating linked list
Force button brushing question 61. rotating linked list
2022-07-25 03:21:00 【GRT should always work hard】

Let the length of the list be n, If you move n Time , It will return to its original position . So every time you move, just move (k%n) Next time .
The idea is to first form the linked list into a ring , Then find the disconnected node .
/** * 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;}
if(k == 0){
return head;}
ListNode tail = head;
int n = 1;
// First, find the last node of the linked list , And count the length of the linked list
while(tail.next != null){
tail = tail.next;
n++;
}
tail.next = head;
ListNode newTail = head;
for(int i = 0; i<(n-1-k%n); i++){
newTail = newTail.next;
}
// The new head node points to the position where the ring is disconnected
ListNode newHead = newTail.next;
newTail.next = null;
return newHead;
}
}
Be careful n The initial value of should be set to 1.
边栏推荐
- Learning record 10
- JS foundation -- task queue and event loop
- Modulenotfounderror: no module named 'pyemd' solution
- Li Kou 279 complete square - dynamic programming
- Learning record Xi
- 05 - MVVM model
- Openlayers draw circles and ellipses
- Using one stack to sort another stack
- Interview question -- event cycle
- Idea configuration
猜你喜欢

Database transactions (often asked)

How does Jupiter notebook change themes and font sizes?

Introduction to Apache Doris grafana monitoring indicators

Decoding webp static pictures using libwebp

How to use two queues to simulate the implementation of a stack

Bubble sort / heap sort

Error: tomee required to support ear/ejb deployment

Hal library serial port for note taking

Message queue (MQ)

File permission management
随机推荐
Riotboard development board series notes (6) -- buildreoot building system image
Common methods of array
Using one stack to sort another stack
The relationship between private domain traffic and fission marketing. What is super app? Can our enterprise own it?
Openlayers draw circles and ellipses
Test question f: statistical submatrix
Enter an integer and a binary tree
Use of stm32cubemonitor part I - data plotting and instrument display
C language_ Defining structures and using variables
Flowlayout in compose
Use reflection to convert RDD to dataframe
B. Making Towers
DOM operation -- get elements and nodes
Ffmpeg 4.3 add custom demuxer
New features commonly used in ES6
NVM installation and use
C language function operation
Riotboard development board series notes (V) -- porting u-boot
mysql_ Record the executed SQL
Analysis of browser working principle