【LeetCode OJ 061】Rotate List
程序员文章站
2024-01-26 12:05:16
题目:Given a list, rotate the list to the right bykplaces, wherekis non-negative.
For examp...
题目:Given a list, rotate the list to the right bykplaces, wherekis non-negative.
For example:
Given1->2->3->4->5->NULL
andk=2
,
return4->5->1->2->3->NULL
.
解题思路:题意为给定一个链表,要求按照给定的位置进行反转。示例代码如下:
public class Solution { public ListNode rotateRight(ListNode head, int k) { if (head == null) return null; ListNode p = head; ListNode q = head; int num = 1;//统计链表元素个数 while (p.next != null) { num++; p = p.next;//p指向尾节点 } int n = 1; if (k >= num) k = k % num;//处理循环反转的情况 while (n < num - k) { n++; q = q.next; } ListNode h = null; if (q.next != null) { //将q后面的节点作为新的头结点 h = q.next; q.next = null; p.next = head; } else { h = head; } return h; } }
上一篇: 令牌桶算法限流
下一篇: 筷子兄弟的病毒营销,只用了一首歌!