Rotate List

来源:互联网 发布:玻璃优化软件破解版 编辑:程序博客网 时间:2024/06/05 06:50

自己搞定的,刚开始题目还没弄清

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可能会很大)

1. list 是空的吗?

2. 连成一个圈,再k 取余, 再转

# Definition for singly-linked list.# class ListNode:#     def __init__(self, x):#         self.val = x#         self.next = Noneclass Solution:    # @param head, a ListNode    # @param k, an integer    # @return a ListNode    def rotateRight(self, head, k):        if head==None:            return head                    cur = head        count = 1        while cur.next!=None:            cur = cur.next            count += 1        cur.next = head                k = k % count        cur = head        for dummy_i in range(count-k-1):            cur = cur.next        newhead = cur.next        cur.next = None                return newhead        


C++

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    ListNode *rotateRight(ListNode *head, int k) {        if (head==NULL){            return head;        }                ListNode *cur = head;        int count = 1;        while (cur->next!=NULL){            cur = cur->next;            count += 1;        }        cur->next = head;                k = k % count;        cur = head;        for(i=1;i<=(count-k-1);i++){            cur = cur->next;        }        ListNode *newhead = cur->next;        cur->next = NULL;                return newhead;            }};



0 0