作者:手机用户2602901563 | 来源:互联网 | 2023-09-23 09:52
【思路】1.将尾指针指向头指针2.并将head指针向后移动kcount–k%count-1位,pheadhead.next就是新链表的头指针3.将head.next置
【思路】
1. 将尾指针指向头指针
2. 并将head指针向后移动k = count – k % count - 1位,phead = head.next就是新链表的头指针
3. 将head.next置空,并返回phead
public ListNode rotateRight(ListNode head, int k) {
if (head == null) return head;
ListNode phead = head;
int count = 1;
while (phead.next != null) {
count++;
phead = phead.next;
}
k = count - k % count - 1;
phead.next = head;
while (k-- > 0)
head = head.next;
phead = head.next;
head.next = null;
return phead;
}
230 / 230test cases passed. Runtime:1 ms Your runtime beats 14.33% of javasubmissions.
欢迎优化!