LeetCode 61 Rotate List

来源:互联网 发布:淘宝店铺介绍文艺句子 编辑:程序博客网 时间:2024/06/13 13:08

题目

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步,然后第二个指针指向头结点,然后两个指针一起走,当第一个指针走到尾结点时,第二个指针后的部分为新链表的前半部分。本来以为如果k大于链表长度则返回原链表。但是提交时遇到错误

Input:
[1,2]
3
Expected::
[2,1]

也就是说当k大于链表长度时,仍是要对链表进行翻转的。考虑到k有可能远大于链表长度,所以放弃用两个指针走的方法。先遍历一遍,得到链表长度 len和尾结点tail,然后计算实际移动的位数k = k % len,找到新的头结点。

/** * 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)              return head;        ListNode* tail = head;        int len = 1;        while(tail->next != NULL) {            tail = tail->next;            len++;        }        k = k % len;        if (k == 0)            return head;        ListNode* cur = head;        int i = len - k;        while(--i)            cur = cur->next;        ListNode* newhead = cur->next;        tail->next = head;        cur->next = NULL;        return newhead;    }};
0 0
原创粉丝点击