首页 > 代码库 > LeetCode_60rotateRight [Rotate List]
LeetCode_60rotateRight [Rotate List]
#pragma warning(disable:4996) #include <cstdio> #include <Windows.h> #include <tchar.h> /* submit time : 4 can not remember request : 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. */ struct ListNode { int val; ListNode* next; ListNode(int x) : val(x), next(NULL) {} }; ListNode *rotateRight(ListNode *head, int k) { if (k == 0 || head == NULL) return head; // get the list length ListNode* pNode = head; int length = 0; while (pNode != NULL) { ++length; pNode = pNode->next; } if (length == 1) return head; k %= length; if (k == 0) k = length; ListNode* vernier = head; while (k--) { vernier = vernier->next; if (vernier == NULL) return head; } ListNode *newtail = head, *newhead = head; while (vernier->next != NULL) { newtail = newtail->next; vernier = vernier->next; } newhead = newtail->next; newtail->next = NULL; vernier->next = head; return newhead; }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。