[Leetcode]旋转链表

荒凉一梦 提交于 2020-02-08 08:44:21

题目

 

代码 

/**
 * 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==nullptr)
       return nullptr;
		auto ptr = head;
		int length = 0;
		while (ptr != nullptr)
		{
			ptr = ptr->next;
			length++;
		}
    
    k=k%length;
     if(k==0)
       return head;
		//54321 2
		auto newHead = ReverseList(head, length);
     if(k==length)
       return newHead;
		//45321 2
		newHead = ReverseList(newHead, k);
		//45123 2
		int num = k;
		auto nextHead = newHead;
		while (num > 0)
		{
			nextHead = nextHead->next;
			num--;
		}
		auto nextNewHead=ReverseList(nextHead, length - k);
		auto connPtr = newHead;
		while (k > 1)
		{
			connPtr = connPtr->next;
			k--;
		}
		connPtr->next = nextNewHead;
		return newHead;

	}
	/*
   * head 开始结点
   * num 翻转的个数
   * return 反转后的头结点
   */
	ListNode* ReverseList(ListNode*head, int num)
	{
		if (head == nullptr || num == 0)
			return nullptr;
		auto realTail = head;

		ListNode* newHead = nullptr;
		ListNode* temp = nullptr;
		while (num>0)
		{
			temp = head->next;
			head->next = newHead;
			newHead = head;
			head = temp;
			num--;
		}
		realTail->next = temp;
		return newHead;
	}
};

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!