您的位置:首页 > 其它

Rotate List ,反转链表的右k个元素

2016-08-09 15:32 330 查看
问题描述:

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
.

算法分析:这个k是可以超过链表长度的,所以要对k取模。

public ListNode rotateRight(ListNode head, int k) {
int lenth = 0;//链表长度
ListNode headd = head;
while (headd != null) {
lenth++;
headd = headd.next;
}
if (head == null || head.next == null || k % lenth == 0) {
return head;
}

ListNode headc = head;
for (int i = 1; i < lenth - k % lenth; i++) {
headc = headc.next;
}
ListNode newHead = headc.next;
ListNode p = newHead;
while (p.next != null) {
p = p.next;
}
p.next = head;
headc.next = null;

return newHead;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: