【leetcode】Rotate List(middle)
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可能比链表长度还大, 需要获取链表长度len, 用 k % len 获取具体需要移动的数字。
class Solution { public: ListNode *rotateRight(ListNode *head, int k) { if(head == NULL || head->next == NULL) return head; ListNode *f = head, *t = head; int len = 1; while(t != NULL && t->next != NULL) { len++; t = t->next; } int mv =len - k % len; //新的头结点在链表中的位置 f = head; while(--mv) { f = f->next; //找到新的头结点的前一个结点 } t->next = head; //尾巴连上最初的头结点 ListNode * newhead = f->next; //新的头结点 f->next = NULL; //新的尾部 return newhead; } };