[LeetCode 题解]: 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.

题意:

翻转链表。

思路:

首先需要读懂题意。题目的描述有问题,应该是将链表的最后k个元素移动到链表的头部。

这道题的本质就是寻找链表的倒数第k个元素。在该点将链表分成两个部分,然后调换顺序即可。

陷阱:

k的长度没有说明,可能k比链表的长度还要大。 设链表的长度为Len,那么移动的节点个数应该为 K%Len.

      

class Solution {
public:
    int getListLength(ListNode *head){
        int len=0;
        ListNode *tmp=head;
        while(tmp){
            len++;
            tmp = tmp->next;
        }
        return len;
    }
    ListNode *rotateRight(ListNode *head, int x) {
        if(head==NULL) return head;  // empty list
        int len = getListLength(head);
        x = x%len; // how many nodes to rotate
        if( len<=1 || x==0) return head;
     
       // find xth node from tail of list
        ListNode *tmp=head;
        ListNode *lend=head;
        ListNode *hstart=head;
        while(tmp->next){
            if(x==0){
                lend = lend->next;
            }else{
                --x;
            }
            tmp = tmp->next;
        }
        
        hstart = lend->next;
        lend->next=NULL;
        tmp->next=head;
        return hstart;
    }
};

转载请注明出处: http://www.cnblogs.com/double-win/ 谢谢!

转载于:https://www.cnblogs.com/double-win/p/3883882.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值