feat: 2025-10-27打卡
This commit is contained in:
45
61.rotate-list.java
Normal file
45
61.rotate-list.java
Normal file
@@ -0,0 +1,45 @@
|
||||
/*
|
||||
* @lc app=leetcode id=61 lang=java
|
||||
*
|
||||
* [61] Rotate List
|
||||
*/
|
||||
|
||||
// @lc code=start
|
||||
/**
|
||||
* 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) {
|
||||
return head;
|
||||
}
|
||||
int len = 0;
|
||||
ListNode cur = head;
|
||||
while(cur != null) {
|
||||
len++;
|
||||
if(cur.next == null) {
|
||||
cur.next = head;
|
||||
break;
|
||||
}
|
||||
cur = cur.next;
|
||||
}
|
||||
k = k % len;
|
||||
ListNode prev = cur;
|
||||
cur = head;
|
||||
for(int i = 0; i < len - k; i++) {
|
||||
cur = cur.next;
|
||||
prev = prev.next;
|
||||
}
|
||||
prev.next = null;
|
||||
return cur;
|
||||
}
|
||||
}
|
||||
// @lc code=end
|
||||
|
||||
Reference in New Issue
Block a user