码迷,mamicode.com
首页 > 其他好文 > 详细

【LeetCode】Rotate List 解题报告

时间:2014-12-17 18:30:18      阅读:148      评论:0      收藏:0      [点我收藏+]

标签:rotate list   linked 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.

【解析】

题意:把链表循环右移k个结点。

不是很难,主要是几个易错点:1)k 可能大于等于链表长度!!!2)链表为空或长度为1。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode rotateRight(ListNode head, int n) {
        if (head == null || n < 1) return head;
        
        //遍历链表求其长度,并找到尾部
        ListNode node = head;
        ListNode tail = null;
        ListNode newhead = null;
        int len = 0;
        while (node != null) {
            len++;
            tail = node;
            node = node.next;
        }
        
        //只有一个结点时,返回原链表即可
        if (len == 1 || n % len == 0) return head;
        
        //把链表首位拼接
        tail.next = head;
        
        //找到右移后的链表尾部
        node = head;
        int i = 1;
        while (i != len - n % len) {
            i++;
            node = node.next;
        }
        newhead = node.next;
        node.next = null;
        
        return newhead;
    }
}


【LeetCode】Rotate List 解题报告

标签:rotate list   linked list   链表   

原文地址:http://blog.csdn.net/ljiabin/article/details/41984511

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!