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.
测试代码(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
if k==0:
return head
first = head
last = head
i = 0
while(i<k):
if last.next==None:
if k==i+1 or i==0:
return head
else:
last = head
k = k%(i+1)
i = 0
continue
last = last.next
i += 1
while last.next!=None:
first = first.next
last = last.next
last.next = head
head = first.next
first.next = None
return head
性能:
参考答案:
# 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 head is None or head.next is None or k == 0: return head
count = 0
t1 = head
t2 = head
while t1 is not None:
count += 1
t1 = t1.next
if k % count == 0: return head
for i in range(count-(k%count)-1):
t2 = t2.next
p = t2.next
t3 = p
t2.next = None
while p.next is not None:
p = p.next
p.next = head
head = t3
return head
性能:
测试代码(c++):
/**
* 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)
return head;
int length = 0;
ListNode *first = head;
ListNode *last = head;
while(last)
{
last = last->next;
length++;
}
if(k==length||length==1||k%length==0)
return head;
k = k%length;
last = head;
while(last->next)
{
if(k<=0)
first = first->next;
last = last->next;
k--;
}
last->next = head;
head = first->next;
first->next = NULL;
return head;
}
};
性能:
参考答案:
class Solution {
public:
ListNode* rotateRight(ListNode* head, int k) {
if(!head) return head;
int len=1; // number of nodes
ListNode *newH, *tail;
newH=tail=head;
while(tail->next) // get the number of nodes in the list
{
tail = tail->next;
len++;
}
tail->next = head; // circle the link
if(k %= len)
{
for(auto i=0; i<len-k; i++) tail = tail->next; // the tail node is the (len-k)-th node (1st node is head)
}
newH = tail->next;
tail->next = NULL;
return newH;
}
};