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

      

  • 相关阅读:
    KKT条件原理
    拉格朗日乘子法
    Java volatile详解
    Java重排序
    Java Socket NIO入门
    Java Socket入门
    TCP三次握手,四次挥手
    Java NIO详解
    cobbler批量安装系统
    nginx详解反向代理,负载均衡,LNMP架构上线动态网站
  • 原文地址:https://www.cnblogs.com/graph/p/3258474.html
Copyright © 2011-2022 走看看