首页 > 学院 > 开发设计 > 正文

LeetCode 61 Rotate List

2019-11-06 07:08:37
字体:
来源:转载
供稿:网友

题目

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; }};
上一篇:zbnet2

下一篇:zbnet1

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表