zoukankan      html  css  js  c++  java
  • [Leetcode]旋转链表

    题目

     

    代码 

    /**
     * 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;
    	}
    };
  • 相关阅读:
    欧拉回路
    2018 年 ACM-ICPC 焦作站现场赛感受
    3.1 基础-抛小球
    2.2 进阶-禁忌雷炎
    初学Java-循环输入直到文件结束
    1.1 基础-取近似值
    1.2 进阶-对称的二叉树
    LEETCODE
    算法
    算法
  • 原文地址:https://www.cnblogs.com/lizhenghao126/p/11053559.html
Copyright © 2011-2022 走看看