[LeetCode82]Rotate List

来源:互联网 发布:js实现一键关注公众号 编辑:程序博客网 时间:2024/04/30 00:39

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.

Analysis

The idea is to get the whole length of the list, get the rotate position.

cut the list from the rotate position, and link the front part and back part.

c++

ListNode *rotateRight(ListNode *head, int k) {        if(head == NULL || k == 0) return head;        ListNode *p=head;        int len = 1;        while(p->next != NULL){            p = p->next;            len++;        }        p->next = head;        int dis = len - k%len;        while(dis !=0){            p = p->next;            dis--;        }        head = p->next;        p->next = NULL;        return head;    }


java

public ListNode rotateRight(ListNode head, int n) {if(head == null || n==0) return head;ListNode p = head;int len = 1;while(p.next!=null){len++;p = p.next;}p.next = head;int dis = len - n%len;while(dis>0){p = p.next;dis--;}head = p.next;p.next = null;        return head;    }


0 0
原创粉丝点击