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.
  • 相关阅读:
    JAVA中==与equals的区别
    spring面试重点
    struts2
    每个新手程序员必看的 SQL 指南
    QueryRunner的使用
    jquery GET POST
    jquery添加元素
    jquery 滑动动画
    jdbc 安装驱动
    为什么做java的web开发我们会使用struts2,springMVC和spring这样的框架?
  • 原文地址:https://www.cnblogs.com/infinityu/p/3077364.html
Copyright © 2011-2022 走看看