转载请注明作者和出处:http://blog.csdn.net/c406495762
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个节点,比如example给出的k=2,那么保留4->5,前面的3个节点1->2->3右移到后面,形成新链表4->5->1->2->3。除此之外,k值也有可能是大于链表长度的,需要取余,获得真实的位移。
Language : c
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* rotateRight(struct ListNode* head, int k) {
int index = 0;
int listlength = 1;
struct ListNode *newlist = (struct ListNode *)malloc(sizeof(struct ListNode));
struct ListNode *tail = (struct ListNode *)malloc(sizeof(struct ListNode));
if(head == NULL){
return NULL;
}
tail = head;
newlist = head;
while(tail->next){ //计算链表长度
tail = tail->next;
listlength++;
}
k = k % listlength; //k可能大于链表的长度
if(k == 0){ //k等于链表长度,不旋转
return head;
}
k = listlength - k; //移动前面listlength-k个节点到右侧,后k个节点不动
tail->next = head; //尾节点连接首节点
for(index; index < k-1; index++){ //找都新链表头
newlist = newlist->next;
}
head = newlist->next; //新链表头
newlist->next = NULL; //链表结尾赋值NULL
return head; //返回链表头结点
}
Language : cpp
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* rotateRight(ListNode* head, int k) {
if(head == NULL){
return NULL;
}
ListNode *tail = head;
int listlength = 1;
while(tail->next){ //计算链表长度
tail = tail->next;
listlength++;
}
k = k % listlength; //k可能大于链表的长度
if(k == 0){ //k等于链表长度,不旋转
return head;
}
k = listlength - k; //移动前面listlength-k个节点到右侧,后k个节点不动
tail->next = head; //尾节点连接首节点
ListNode *newlist = head;
for(int index = 0; index < k-1; index++){ //找都新链表头
newlist = newlist->next;
}
head = newlist->next; //新链表头
newlist->next = NULL; //链表结尾赋值NULL
return head; //返回链表头结点
}
};
Language:python
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def rotateRight(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
"""
if not head:
return None
tail = head
listlength = 1
while tail.next:
tail = tail.next
listlength += 1
k = k % listlength
if k == 0:
return head
k = listlength - k
tail.next = head
newlist = head
for each in range(k - 1):
newlist = newlist.next
head = newlist.next
newlist.next = None
return head
LeetCode题目汇总: https://github.com/Jack-Cherish/LeetCode