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;
        }
  • 相关阅读:
    数据流图和数据流程图的定义与组成元素
    敏捷开发3种角色
    WBS
    开发流程
    结对编程
    笔记
    登录注册界面维护2----注册界面进行Toast提示
    登录注册界面修改错误
    听说
    “学习链接篇”
  • 原文地址:https://www.cnblogs.com/hellowooorld/p/6674159.html
Copyright © 2011-2022 走看看