LeetCode – Rotate List

题目:

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

解题:

1. 遍历链表,计算链表个数len,并将链表头尾相连;
2. 从head遍历节点,找到要到第 len-(k%len) 个的前一个节点cur ;
3. cur->next 做为新的头节点返回。 

实现:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */


struct ListNode* rotateRight(struct ListNode* head, int k){
    int len = 0;
    struct ListNode *cur=head;
    
    if (NULL == head){
        return head;
    }
    len = 1;
    while (cur->next!=NULL){
        cur=cur->next;
        len += 1;
    }
    cur->next = head;
    
    int r=len-(k%len);
    
    for (int i=0; i<r; i++){
        cur = cur->next;
    }
    
  
    struct ListNode *newhead;
    newhead = cur->next;
    cur->next = NULL;
    
    return newhead;

}
Runtime: 0 ms
Memory Usage: 7.3 MB
时间复杂度O(n), 空间复杂度O(1)

Be First to Comment

发表评论

电子邮件地址不会被公开。 必填项已用*标注