Rotate List

来源:互联网 发布:易语言用数据库做登录 编辑:程序博客网 时间:2024/05/19 14:51

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是可以大于链表长度的 这个起初也没注意到 报错后才想到 所以第一步是计算链表长度len 然后针对 n%len进行翻转  代码如下:

public class Solution {    public ListNode rotateRight(ListNode head, int n) {       if(head==null||head.next==null||n==0)return head;ListNode slow=head;ListNode fast=head;int count=0;while(fast!=null){        count++;        fast=fast.next;}n=n%count;count=0;if(n==0) return head;fast=head;while(fast.next!=null){count++;if(count>n){fast=fast.next;slow=slow.next;}else{fast=fast.next;}}ListNode tmp=new ListNode(0);tmp.next=slow.next;fast.next=head;slow.next=null;return tmp.next;    }}


0 0
原创粉丝点击