题目描述:
Given a list, rotate the list to the right by k places, where k is non-negative.
Example:
Given 1->2->3->4->5->NULL and k = 2, return 4->5->1->2->3->NULL.
解题思路:
这题如果用递归的话可以只需要遍历一遍就可以得到从右数的节点。但是题目给的k会大于n,还是要得到遍历一遍链表得到长度,这样就失去了递归的优势。所以我换了个方法,先得到链表的长度len,再将k模len,从左边开始数。
代码:
/** * 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 len = 1; ListNode* tail = head, *newone = head; while(tail->next){ tail = tail->next; len++; } tail->next = head; k %= len; for(int i = 1; i < len-k; i++) newone = newone->next; head = newone->next; newone->next = NULL; return head; } };