zoukankan      html  css  js  c++  java
  • [leetcode-61-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.

    思路:

    首先求出list的长度length,然后将最后一个结点指向初始的头结点,

    然后从该初始结点出发,指针向后移动length-k次,

    找到新链表的尾结点,然后把它的next置为NULL。

    ListNode* rotateRight(ListNode* head, int k)
        {
            ListNode* result;
            if (k == 0 || head == NULL) return head;
            int length = 1;
            ListNode* temp = head;
            while (head != NULL && head->next != NULL)
            {
                head = head->next;
                length++;
            }
            k %= length;
            head->next = temp;//head 目前为最后一个结点的指针 指向初始时候的头部结点
            for (int i = 0; i < length - k-1;i++)
            {
                temp = temp->next;
            }
             result = temp->next;
            temp->next = NULL;
            return result;
        }
  • 相关阅读:
    VERSIONINFO Resource
    WCF 学习文摘
    hook 学习
    COM 学习
    ActiveX开发
    Word 开发资料集合
    Loops with PL/SQL
    TWain 在 Qt4 中的调用方法
    从 TWAIN 设备中扫描图像
    Qt enum使用总结
  • 原文地址:https://www.cnblogs.com/hellowooorld/p/6674159.html
Copyright © 2011-2022 走看看