zoukankan      html  css  js  c++  java
  • 面试题27:单链表向右旋转k个节点

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

    For example:
    Given1->2->3->4->5->NULLand k =2,
    return4->5->1->2->3->NULL.

     1 /**
     2  * Definition for singly-linked list.
     3  * struct ListNode {
     4  *     int val;
     5  *     ListNode *next;
     6  *     ListNode(int x) : val(x), next(NULL) {}
     7  * };
     8  */
     9 class Solution {
    10 public:
    11     ListNode *rotateRight(ListNode *head, int k) {
    12         if(head == nullptr || head->next == nullptr) return head;
    13 
    14         int length = 0;
    15         ListNode* p = head;
    16         while(p){
    17             length++;
    18             p = p->next;
    19         }
    20         k = k % length;
    21         if(k == 0) return head;
    22         int m = length - k;
    23         p = head;
    24         while(m > 1){
    25             p = p->next;
    26             m--;
    27         }
    28         ListNode* right = p->next;
    29         p->next = nullptr;
    30         p = right;
    31         while(p->next){
    32             p = p->next;
    33         }
    34         p->next = head;
    35         head = right;
    36         return head;
    37     }
    38 };
  • 相关阅读:
    绿色版 notepad++ 添加鼠标右键菜单
    Scala 安装与配置
    Scala 神奇的下划线 _
    Kafka 安装部署
    Pulsar 下一代消息平台
    Sqoop 安装部署
    Flume 常用配置项
    Android-selector
    android- 9patch
    有关内存的思考题
  • 原文地址:https://www.cnblogs.com/wxquare/p/6877183.html
Copyright © 2011-2022 走看看