来自 澳门新葡亰 2019-09-28 04:31 的文章
当前位置: 澳门新葡亰app > 澳门新葡亰 > 正文

Leetcode:61. Rotate List

Description

Given a list, rotate the list to the right by k places, where k is non-negative.

Example

Given 1->2->3->4->5->NULL and k = 2,return 4->5->1->2->3->NULL.

思路

  • 先遍历一遍链表,记录长度,同时记录最后一个节点
  • 修正k的大小,找到旋转后的头结点,和它的前一个节点
  • 按照题目要求重新链接链表

代码

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode : val, next {} * }; */class Solution {public:    ListNode* rotateRight(ListNode* head, int k) {        if return head;        if return NULL;                ListNode *ptr = head, *tail = NULL;        int len = 0;        //找出链表的长度        while{            len++;            tail = ptr;            ptr = ptr->next;        }                //修正k的值        k = k % len;        if return head;                int step = len - k + 1;        ListNode *fastPtr = head;        ptr = head;        while(step - 1 > 0){            step--;            ptr = fastPtr;            fastPtr = fastPtr->next;        }                if{            tail->next = head;            ptr->next = NULL;            return fastPtr;        }                return head;    }};

本文由澳门新葡亰app发布于澳门新葡亰,转载请注明出处:Leetcode:61. Rotate List

关键词: