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.

     
     思路:先遍历一遍,得出链表长度,注意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 };
  • 相关阅读:
    uva 1637 Double Patience
    Emacs ^ Vim
    uva 11181 Probability|Given
    uva 10491 Cows and Cars
    uva 1636 Headshot
    hdu 4336 Card Collector
    zoj 3640 Help Me Escape
    Codeforces 148 D Bag of mice
    hdu 4405 Aeroplane chess
    hdu 3853 LOOPS
  • 原文地址:https://www.cnblogs.com/xiaoying1245970347/p/4701274.html
Copyright © 2011-2022 走看看