zoukankan      html  css  js  c++  java
  • 61. 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.

    k=2 就是向右移动2次

     1 /**
     2  * Definition for singly-linked list.
     3  * struct ListNode {
     4  *     int val;
     5  *     struct ListNode *next;
     6  * };
     7  */
     8 struct ListNode* rotateRight(struct ListNode* head, int k) {
     9     struct ListNode *cur;
    10     cur = head;
    11     int n = 1;
    12     if(head == NULL)
    13         return NULL;
    14     while(cur->next != NULL)                 //求链表长度,把cur定位到尾结点
    15     {
    16         cur = cur->next;
    17         n++;
    18     }
    19     k = n - k % n;                  //注意K有可能大于链表长度 要取余数
    20     cur->next = head;
    21     cur = head;
    22     k--;
    23     while(k)                                   //cur移动到断开前的位置
    24     {
    25         cur = cur->next;
    26         k--;
    27     }
    28     head = cur->next;
    29     cur->next = NULL;
    30     return head;
    31 }
  • 相关阅读:
    String API
    正则表达式语法
    正则表达式定义与创建
    jQuery——子元素筛选器
    基本筛选器
    内置对象和包装类型
    栈和队列
    web前端css实现六边形效果
    jquery选择器
    AE导出mov
  • 原文地址:https://www.cnblogs.com/boluo007/p/5503444.html
Copyright © 2011-2022 走看看