【LeetCode OJ 061】Rotate List
程序员文章站
2022-05-12 20:33:45
题目: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; } }
上一篇: Oracle控制文件丢失了怎么办?
下一篇: Oracle日常性能查看