zoukankan      html  css  js  c++  java
  • LeetCode——rotate-list

    Question

    Given a list, rotate the list to the right by k places, where k is non-negative.
    For example:
    Given1->2->3->4->5->NULLand k =2,
    return4->5->1->2->3->NULL.

    Solution

    1. 典型的fast-slow指针问题。

    2. 有很多小细节,k指向最后一个节点,k指向第一个节点,k大于所有节点的个数,链表中节点个数为1,k为0,都要考虑进去。

    Code

    /**
     * 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) {
            if (head == NULL || k == 0)
                return head;
            int count = 0;
            ListNode* tmp = head;
            while (tmp != NULL) {
            	tmp = tmp->next;
                count++;
            }
            if (k > count) {
                if (k % count == 0)
                    return head;
                k = k % count;
            }
            
            ListNode* slow = head;
            ListNode* fast = head;
            int i;
            for (i = 0; i < k - 1; i++) {
                if (fast != NULL) {
                    fast = fast->next;
                } else
                    return head;
            }
            
            ListNode* pre = NULL;
            while (fast != NULL && fast->next != NULL) {
                pre = slow;
                slow = slow->next;
                fast = fast->next;
            }
            if (pre == NULL)
                return head;
            else
                pre->next = NULL;
            if (fast != NULL)
            	fast->next = head;
            head = slow;
            
            return head;
        }
    };
    
  • 相关阅读:
    ul做导航栏
    论布局,bfc,margin塌陷和合并,经典bug
    mon-hom
    新浪下拉菜单模仿
    JQ筛选方法,筛选父子元素
    JQuery筛选选择器
    JQuery隐式迭代
    python 和 C# DES加密
    交互设计[1]--设计心理学
    javascript学习(9)——[设计模式]单例
  • 原文地址:https://www.cnblogs.com/zhonghuasong/p/7766285.html
Copyright © 2011-2022 走看看