zoukankan      html  css  js  c++  java
  • Leetcode:61. Rotate List

    Description

    Given a list, rotate the list to the right by k places, where k is non-negative.

    Example

    Given 1->2->3->4->5->NULL and k = 2,
    return 4->5->1->2->3->NULL.
    

    思路

    • 先遍历一遍链表,记录长度,同时记录最后一个节点
    • 修正k的大小,找到旋转后的头结点,和它的前一个节点
    • 按照题目要求重新链接链表

    代码

    /**
     * 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(k == 0) return head;
            if(!head) return NULL;
            
            ListNode *ptr = head, *tail = NULL;
            int len = 0;
            //找出链表的长度
            while(ptr){
                len++;
                tail = ptr;
                ptr = ptr->next;
            }
            
            //修正k的值
            k = k % len;
            if(k== 0) return head;
            
            int step = len - k + 1;
            ListNode *fastPtr = head;
            ptr = head;
            while(step - 1 > 0){
                step--;
                ptr = fastPtr;
                fastPtr = fastPtr->next;
            }
            
            if(fastPtr){
                tail->next = head;
                ptr->next = NULL;
                return fastPtr;
            }
            
            return head;
        }
    };
    
  • 相关阅读:
    React 生命周期及setState原理分析
    React Vue Angular 对比
    盒模型(一)
    CSS尺寸 rem与em原理与区别(二)
    HTTP 状态码
    React渲染机制
    HTTP三次握手四次挥手
    Java常见算法
    SharedPreferences存储数据
    解决ListView滑动上下出现阴影
  • 原文地址:https://www.cnblogs.com/lengender-12/p/6891839.html
Copyright © 2011-2022 走看看