zoukankan      html  css  js  c++  java
  • [LeetCode]Rotate List

    链表题again. 实现链表节点的循环移位. 注意k的边界范围。

    思路:

    1. 得到链表长度N,指针end指向尾节点

    2. 找到新链表头节点在老链表中的前驱节点,记为p. p = N-k%N-1

    3. end指向原链表head节点,此时链表为环状。更新链表头节点位置,head指向p->next。将p->next置为NULL,成为尾节点。

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

    For example:
    Given 1->2->3->4->5->NULL and k = 2,
    return 4->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         // Note: The Solution object is instantiated only once and is reused by each test case.
    13         if(head == NULL || k==0)
    14             return head;
    15         
    16         ListNode *end = head;
    17         int N = 1;
    18         while(end->next)
    19         {
    20             ++N;
    21             end = end->next;
    22         }
    23         int p = N-k%N-1;
    24         ListNode *pre = head;
    25         if(p<0)
    26             return head;
    27         else
    28         {
    29             for(int i=0; i<p; ++i)
    30                 pre = pre->next;
    31             end->next = head;
    32             head = pre->next;
    33             pre->next = NULL;
    34         }
    35         return head;
    36     }
    37 };
  • 相关阅读:
    服务器运维
    mysq配置
    PHP-FPM进程数的设定
    vsftpd 安装配置详细教程
    php-fpm性能优化
    如果不知道MySQL当前使用配置文件(my.cnf)的路径的解决方法
    搭建linux+nginx+mysql+php环境
    PHP 页面编码声明方法详解(header或meta)
    Linux内核的一些知识。
    Connector框架笔记
  • 原文地址:https://www.cnblogs.com/practice/p/3387771.html
Copyright © 2011-2022 走看看