Rotate List

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.


Analysis:

1. The list could be empty, i.e. head == null. 

2. Build a circle based on the original list andfind the number of nodes of such list. These two things can be done simultaneously by traversing the list one time.

3. Find the index of the last node of the newly generated list, which should be num_nodes - (n % num_nodes). 

4. The head of the new list should be the next node of the last node, since the whole list is a circle now.

5. Break the circle by appropriately handling the first and last nodes of the newly created list. 


/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public int getLengthAndBuildCycle(ListNode head, ListNode cur, int len) {
        while(cur.next != null) {
            cur = cur.next;
            len++;
        }
        cur.next = head;    // build a circle, important logic!!!
        return len;
    }
    
    public ListNode rotateRight(ListNode head, int n) {
        if(n==0 || head==null) return head;
        ListNode cur=head, res=head;
        int len = getLengthAndBuildCycle(head, cur, 1);       // get the length of this list
        for(int i=1; i<len-n%len; i++) {    // res points the last node after this loop
            res = res.next;
        }
        cur = res;              // cur points to the last node of the newly generated list
        res = res.next;         // res points to the first node of the newly generated list
        cur.next = null;
        return res;
    }
}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值