zoukankan      html  css  js  c++  java
  • 170. 旋转链表

    170. 旋转链表 

     

    给定一个链表,旋转链表,使得每个节点向右移动k个位置,其中k是一个非负数

    样例

    给出链表1->2->3->4->5->null和k=2

    返回4->5->1->2->3->null

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    
    
    class Solution {
    public:
        /*
         * @param head: the List
         * @param k: rotate to the right k places
         * @return: the list after rotation
         */
        ListNode * rotateRight(ListNode * head, int k) {
            // write your code here
             if (!head) return NULL;
            int n = 1;
            ListNode *cur = head;
            while (cur->next) {
                ++n;
                cur = cur->next;
            }
            cur->next = head;
            int m = n - k % n;
            for (int i = 0; i < m; ++i) {
                cur = cur->next;
            }
            ListNode *newhead = cur->next;
            cur->next = NULL;
            return newhead;
    
        }
    };
    

      

  • 相关阅读:
    奔跑的绵羊js
    13.差分
    12.子矩阵的和
    11.前缀和
    10.高精度除法
    9.高精度乘法
    8.高精度减法
    7.高精度加法
    6.数的三次方根
    5.数的范围
  • 原文地址:https://www.cnblogs.com/kanekiken/p/8033521.html
Copyright © 2011-2022 走看看