关闭

leetcode #61 in cpp

标签: cppleetcode
73人阅读 评论(0) 收藏 举报
分类:

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.


Solution: 

If k < length of the node, then we use two pointers to find the new head in the list as what we do in #19, and then we delete the link between the new head and its parent, and add link from the tail to the original head. 

1->2->3->4, say 3 is the new head


1->2->null 3->4----

|______________|

link from tail to original head


If k >= length of the node. we rotate k%length. It is simply like rotating a circle.

Code:

/**
 * 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) return head;
        if(!head->next) return head;
        
        int len = 0;
        ListNode *cur = head;
        
        while(cur){//calculate how long the linked list is
            len++;
            cur = cur->next;
        }
        
        k %=len;
        if(k==0) return head;
        
        ListNode *prev = head;
        cur = head;
        len =0;
        while(len<k && cur->next){//separate cur k distance from prev
            cur = cur->next;
            len++;
        }
        while(cur->next){//move cur to tail. prev->next is the beginning of the section we are to rotate
            cur = cur->next;
            prev = prev->next;
        }
        cur->next = head;//link tail to original head
        ListNode *newHead = prev->next;//get new head
        prev->next = NULL;//put prev as tail
        
        return newHead;
        
    }
};


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:7994次
    • 积分:1395
    • 等级:
    • 排名:千里之外
    • 原创:139篇
    • 转载:0篇
    • 译文:0篇
    • 评论:0条
    文章分类
    文章存档