题目链接:https://leetcode.com/problems/rotate-list/
题目:Given a list, rotate the list to the right by k places, where k is non-negative.
For example:
Given 1->2->3->4->5->NULL
and k = 2
,
return 4->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;
}
}