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.
Linked List、Two Pointers
中等
题目意思是按给定的value旋转单链表。我的做法是先获取链表的长度,然后从头遍历,找到新表的头结点,然后将新表结尾指向到旧表的头。
struct ListNode* rotateRight(struct ListNode* head, int k)
{
struct ListNode *p, *t, *q, *ret;
int length = 0;
if(!head)
return NULL;
p = head;
while(p)
{
p = p->next;
length++;
}
p = head;
if(k>length)
k = length - k%length;
else
k = (length-k)%length;
while(p && k>1)
{
q = p;
p = p->next;
k--;
}
if(!p->next || k == 0)
return head;
ret = t = p->next;
p->next = NULL;
while(t)
{
q = t;
t = t->next;
}
q->next = head;
return ret;
}
这里看到别人写的一个更简单的,先找到旧表的尾节点,将尾节点的NEXT指向旧表的头,然后再去遍历找到新表的头结点
struct ListNode* rotateRight(struct ListNode* head, int k)
{
int i;
if(head == NULL || k == 0) {
return head;
}
struct ListNode* p = head;
int len = 1;
while(p->next != NULL) {
p = p->next;
len++;
}
p->next = head;
k %= len;
for(i = 0; i < len - k; i++) {
p = p->next;
}
head = p->next;
p->next = NULL;
return head;
}