leetcode 61.Rotate List

来源:互联网 发布:网易企业邮箱域名设置 编辑:程序博客网 时间:2024/05/23 18:36

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移动k个位置,这里需要注意的是k可能大于list的长度,因此首先求取list的长度是需要的。
本题最主要设置2个指针,位置相差k。

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { val = x; } * } */public class Solution {    public ListNode rotateRight(ListNode head, int k) {        if(head == null){            return head;        }        ListNode pre = head;        int length = 0;        while(pre != null){            pre = pre.next;            length++;        }        k = k % length;        pre = head;        ListNode tal = head;        for(int j = 0; j < k; j++){            tal = tal.next;        }        while(tal.next != null){            tal = tal.next;            pre = pre.next;        }        tal.next = head;        head = pre.next;        pre.next = null;        return head;    }}
这里出现冗余的地方是两个指针的位置,可以看到,最后tal指针停下来的位置是list的最后一个节点,与求长度时pre指针的停下的位置相同,因此tal指针不需要额外再使用循环了,只需要找到pre的位置即可。
<pre name="code" class="java">/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { val = x; } * } */public class Solution {    public ListNode rotateRight(ListNode head, int k) {        if(head == null){            return head;        }        ListNode pre = head;        ListNode tal = head;        int length = 1;        while(tal.next != null){            tal = tal.next;            length++;        }        k = k % length;        for(int i = 0; i < length - k - 1; i++){            pre = pre.next;        }        tal.next = head;        head = pre.next;        pre.next = null;        return head;    }}

虽然减少了一个for循环,但从测试结果来看,时间上差不多,都是1ms,但这样思路也更清晰了些。

0 0
原创粉丝点击