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;
    
        }
    };
    

      

  • 相关阅读:
    day10 作业
    文件操作
    字符编码
    元组、字典、集合内置方法, 深浅拷贝
    day07作业
    一周总结
    mysql操作进阶
    mysql操作篇续
    mysql-操作篇
    mysql的安装
  • 原文地址:https://www.cnblogs.com/kanekiken/p/8033521.html
Copyright © 2011-2022 走看看