61. Rotate List

来源:互联网 发布:php彩票网站系统 编辑:程序博客网 时间:2024/04/20 05:54

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.

My solution

public ListNode rotateRight(ListNode head, int k) {        if(head == null || head.next == null || k == 0){            return head;        }        ListNode dummy = new ListNode(-1);        dummy.next = head;        int count = 1;        while(head.next != null){            head = head.next;            count++;        }        if(count == k){            return dummy.next;        }        if(count < k){        k = k % count;        }        int count2 = 0;        ListNode newHead = dummy;        //First version didn't realize [1, 2] 2        /*ListNode newHead = dummy.next;        while(newHead != null){        count2 ++;        if(count2 == count - k){                break;            }              newHead = newHead.next;                        }*/        while(newHead != null){        if(count2 == count - k){                break;            }              newHead = newHead.next;            count2 ++;            }        head.next = dummy.next;        dummy.next = newHead.next;        newHead.next = null;        return dummy.next;    }

Solution 2 Two pointer, more elegant solution.

public static ListNode rotateRight2(ListNode head, int k) {        if(head == null || head.next == null){            return head;        }        ListNode dummy = new ListNode(-1);        dummy.next = head;        ListNode fast = dummy;        ListNode slow = dummy;        int i;        for(i = 0; fast.next != null; i++){            fast = fast.next;        }        for(int j = 0; j < i - k % i; j++){            slow = slow.next;        }        fast.next = dummy.next;        dummy.next = slow.next;        slow.next = null;        return dummy.next;    }

Solution 3 No need to count the length of the linked list

https://leetcode.com/discuss/7687/anyone-solve-the-problem-without-counting-the-length-of-list

1. Make the linkedlist to a circle

2.Use two pointers, when the fast one reaches the end, then jump to the head


0 0
原创粉丝点击