【LeetCode】Rotate List

/**
 * 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 == NULL)
		return NULL;
		if(k==0)
		return head;
	int len = 1;
	ListNode *tmp,*ptr;
	ListNode *newHead;
	tmp = head; ptr = head;
	while (tmp->next)
	{
		len++;
		tmp = tmp->next;
	}
	tmp->next = head;
	int step;
	step = len - k%len;
	for (int i = 1; i < step; i++)
	{ 
		ptr = ptr->next;
	}
	newHead = ptr->next;
	ptr->next = NULL;
	return newHead;
    }
};

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章