本文主要是介绍Leetcode132: 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
.
需要注意的是k的值可能比链表的长度大,所以需要取余。再定义两个指针,一个超前另一个k步,然后同时向右走,直到前面的指针到达尾部,那么后面的指针所指的节点就是新的链表的尾部。
/*** 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;ListNode* l = head;ListNode* r = head;int n = 1;while(l->next){l = l->next;n++;}k %= n;l = head;while(k){r = r->next;k--;}while(r->next){r = r->next;l = l->next;}r->next = head;head = l->next;l->next = NULL;return head;}
};
这篇关于Leetcode132: Rotate List的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!