leetcode 61

61. Rotate List
Add to List

Share
Given a linked list, rotate the list to the right by k places, where k is non-negative.

Example 1:

Input: 1->2->3->4->5->NULL, k = 2
Output: 4->5->1->2->3->NULL
Explanation:
rotate 1 steps to the right: 5->1->2->3->4->NULL
rotate 2 steps to the right: 4->5->1->2->3->NULL
Example 2:

Input: 0->1->2->NULL, k = 4
Output: 2->0->1->NULL
Explanation:
rotate 1 steps to the right: 2->0->1->NULL
rotate 2 steps to the right: 1->2->0->NULL
rotate 3 steps to the right: 0->1->2->NULL
rotate 4 steps to the right: 2->0->1->NULL

  leetcode 61 题,给到一个链表, 顺时针旋转k个,求结果

 

  解题思路,移动k个,新建两个指针,让前一个指针前进k个格子,然后后一个指针再同时前进,这样就可以找到切割点了。

  需要注意的是,k有可能是会超出链表长度的, 需要进行处理,还有就是注意一些特殊情况的排除

/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */

 /*
 本题是说将一串链表顺时针旋转k个,
*/
func rotateRight(head *ListNode, k int) *ListNode {
    if k == 0 || head==nil {
        return head
    }
    var ptr1, ptr2 *ListNode = head, head
    // var ptr2 *ListNode = head
    var i int = 0
    // first try to find the diff node length
    for ; i < k; i ++ {
        if ptr1.Next == nil {
            break
        } else {
            ptr1 = ptr1.Next
        }
    }

    // the k is to big, i+1 is the length of the list node
    if i < k {
        i = k % (i + 1)
        return rotateRight(head, i)
    }

    // to move to the tail
    for {
        if ptr1.Next == nil {
            break
        } else {
            ptr1 = ptr1.Next
            ptr2 = ptr2.Next
        }
    }

    //do split
    ptr1.Next = head
    head = ptr2.Next
    ptr2.Next = nil
    return head
}

 

你可能感兴趣的:(leetcode 61)