leetcode-61. Rotate List

来源:互联网 发布:sql批量insert 编辑:程序博客网 时间:2024/05/22 07:57

leetcode-61. 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.

思路大致如下:
首先创立一个哑节点,然后建立两个指针都指向这个哑节点,然后维护两个整型常量,一个维护当前两个指针之间的距离,一个记录整个列表的节点数量。
然后移动r节点,直到两节点之间的距离为k,然后同时移动两个节点,直到右节点到达尾部。
然后判断两指针之间的距离是否为k,如果为k则说明列表的长度大于k,进行指针指向调整,如果不等于,则说明列表长度小于k,对k求sum的余然后重新计算rotateRight,
进行指针调整的时候,还会出现一种特殊的情况就是k正好等于sum,这样如果进行指针调整,则会形成一个环,所以需要排除这个情况。我第一遍做的时候没有考虑这个

/** * 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 || k ==0) return head;        int count = 0, sum=0;        ListNode dump = new ListNode(0);        dump.next = head;        ListNode l = dump;        ListNode r = dump;        while(r.next!=null){            r = r.next;            sum++;            if(count==k){                l=l.next;            }else{                count++;            }            // System.out.println(l.val+" "+r.val);        }        if(count==k){            if(k==sum) return head;            ListNode ret = l.next;            r.next = dump.next;            l.next = null;            return ret;        }else{            k = k % sum;            return rotateRight(head,k);        }    }}
0 0
原创粉丝点击