zoukankan      html  css  js  c++  java
  • [面试真题] LeetCode:Rotate List

    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.

    解法:游标指针从头节点向后移动,当指向尾节点时,得到链表长度len,同时将链表头尾相连,接着游标再向后移动 k % len 步得到结果链表的尾节点。

     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         // Start typing your C/C++ solution below
    13         // DO NOT write int main() function
    14         if(head){
    15             int len = 1;
    16             ListNode *p = head;
    17             while(p->next){
    18             p = p->next;
    19             len++;
    20             }
    21             p->next = head;
    22             k %= len;
    23             int step = len - k;
    24             while(step>0){
    25                 p = p->next;
    26                 step--;
    27             }
    28             head = p->next;
    29             p->next = NULL;
    30         }
    31         return head;
    32     }
    33 };

    Run Status: Accepted!
    Program Runtime: 56 milli secs

    Progress: 229/229 test cases passed.
  • 相关阅读:
    Linux基础命令练习题答案7.9
    Linux基础练习题7.9
    Linux基础练习题答案7.8
    Linux基础练习题7.8
    12 drf精华总结
    11 drf(RBAC)基于角色的权限控制
    10 drfJWT认证
    09 drf自动生成接口文档
    08 drf分页器
    Python 3.9正式版,新特性提前一睹为快
  • 原文地址:https://www.cnblogs.com/infinityu/p/3077364.html
Copyright © 2011-2022 走看看