• 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.

     
     思路:先遍历一遍,得出链表长度,注意k可能大于len令k%=len,将尾节点next指针指向首节点,形成一个环 ,然后接着跑len-k步, 从这里断开,就是要求的结果。
     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         if(head==NULL || k==0) return head;
    13         
    14         int len=1;
    15         ListNode *p=head;
    16         while(p->next)
    17         {
    18             len++;
    19             p=p->next;
    20         }
    21         
    22         int step=len-k%len;
    23         
    24         p->next=head;//尾节点next指针指向首节点
    25         //向后走step步 然后断开
    26         
    27         for(int i=0;i<step;i++)
    28             p=p->next;
    29         
    30         head=p->next;
    31         p->next=NULL;
    32         
    33         return head;
    34     }
    35 };
  • 相关阅读:
    C#中的委托和事件的使用
    C#中Attribute/特性的使用
    Eclipase + CDT
    设计模式总结
    Nginx源码编译
    Nginx自定义扩展模块
    电池的寿命
    大盗阿福
    河中跳房子
    An Easy Problem
  • 原文地址:https://www.cnblogs.com/xiaoying1245970347/p/4701274.html
Copyright © 2020-2023  润新知