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>length 时,我以为origin list 不动就行,结果好些case过不了,看了别人的代码才知道要 k%= length 真心想不通为什么,也懒得弄这种恶心的东西。面试遇到这种题目直接问面试官这种奇葩情况怎么处理就行。 

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode *rotateRight(ListNode *head, int k) {
            // Start typing your C/C++ solution below
            // DO NOT write int main() function
            if(head == NULL || k == 0) return head;
    		ListNode *p, *q;
    		p = head;q= p;
    		while(q &&--k){
    			q = q->next;
    		}
    		if(k >0 || NULL == q) return head; 
    		ListNode *pre = NULL;
    		
    		while(q->next){
    			pre = p;
    			p = p->next;
    			q = q->next;
    		}
    		q ->next = head;
    		head  = p;
    		pre ->next = NULL;
    		return head;
    		
        }
    };
    

      

  • 相关阅读:
    我的省选 Day -9
    我的省选 Day -10
    我的省选 Day -11
    我的省选 Day -12
    我的省选 Day -13
    [NOI2013]快餐店
    我的省选 Day -14
    杭电多校2020第7场-E Expectation
    「联合省选2020」组合数问题
    UR#19 通用评测号
  • 原文地址:https://www.cnblogs.com/graph/p/3258474.html
Copyright © 2011-2022 走看看