leetcode #61 in cpp

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;
        
    }
};


阅读更多
文章标签: cpp leetcode
个人分类: interview
想对作者说点什么? 我来说一句

LeetCode cpp最新中文题解.pdf

2018年01月10日 866KB 下载

没有更多推荐了,返回首页

不良信息举报

leetcode #61 in cpp

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭