[leetcode]61. Rotate List@Java解题报告

来源:互联网 发布:折八百淘宝商城马甲 编辑:程序博客网 时间:2024/06/05 02:32

https://leetcode.com/problems/rotate-list/description/

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.




这道题主要先理解题意,就是倒着数k个node,从那开始到结尾和之前那部分对调,那个例子就是,4->5拿前面来,1->2->3拿后面去。



package go.jacob.day817;/** * 61. Rotate List * @author Jacob */public class Demo2 {/* * 这种方法考虑了k=0的情况。 * 当k=0,cur和pre都为链表最后一个节点 * 运行cur.next = preHead.next;preHead.next = pre.next;pre.next = null;后 * 链表结构没有改变 */public ListNode rotateRight(ListNode head, int k) {if (k == 0 || head == null || head.next == null)return head;ListNode preHead = new ListNode(0);preHead.next = head;ListNode cur = head;ListNode pre = head;int total;for (total = 1; cur.next != null; total++)cur = cur.next;for (int i = 1; i < total - k % total; i++) {pre = pre.next;}cur.next = preHead.next;preHead.next = pre.next;pre.next = null;return preHead.next;}}


原创粉丝点击