首页 > 其他 > 详细

LeetCode_60rotateRight [Rotate List]

时间:2014-07-25 00:04:04      阅读:376      评论:0      收藏:0      [点我收藏+]
#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;
}



LeetCode_60rotateRight [Rotate List],布布扣,bubuko.com

LeetCode_60rotateRight [Rotate List]

原文:http://my.oschina.net/ITHaozi/blog/294606

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!