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;
    	}
    };
  • 相关阅读:
    hdu5754_找规律+威佐夫博弈
    codeforce645C_尺取法
    hdu4336_容斥dp
    poj3071_概率dp
    codeforces148D_推论题
    poj2151_概率dp
    hdu3853_概率dp
    POJ 1410 判断线段与矩形交点或在矩形内
    POJ 1066 Treasure Hunt 线段相交判断
    POJ 2653 Pick-up sticks 判断线段相交
  • 原文地址:https://www.cnblogs.com/lizhenghao126/p/11053559.html
Copyright © 2011-2022 走看看