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.
Analysis
The idea is to get the whole length of the list, get the rotate position.
cut the list from the rotate position, and link the front part and back part.
c++
ListNode *rotateRight(ListNode *head, int k) {
if(head == NULL || k == 0) return head;
ListNode *p=head;
int len = 1;
while(p->next != NULL){
p = p->next;
len++;
}
p->next = head;
int dis = len - k%len;
while(dis !=0){
p = p->next;
dis--;
}
head = p->next;
p->next = NULL;
return head;
}java
public ListNode rotateRight(ListNode head, int n) {
if(head == null || n==0) return head;
ListNode p = head;
int len = 1;
while(p.next!=null){
len++;
p = p.next;
}
p.next = head;
int dis = len - n%len;
while(dis>0){
p = p.next;
dis--;
}
head = p.next;
p.next = null;
return head;
}

本文详细介绍了如何使用C++和Java语言实现旋转链表的功能,包括获取链表长度、计算旋转位置、断开链表并重新连接前后部分以完成旋转操作。
1060

被折叠的 条评论
为什么被折叠?



