首页 > 其他 > 详细

Rotate List || LeetCode

时间:2015-06-07 18:49:08      阅读:159      评论:0      收藏:0      [点我收藏+]
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* rotateRight(struct ListNode* head, int k) {
    struct ListNode *sentry,*p,*temp,*tail;
    int    len=0,index;
    
    if(head==NULL)return NULL;
    sentry=(struct ListNode *)malloc(sizeof(struct ListNode));
    sentry->next=NULL;
    p=head;
    tail=sentry;
    while(1){
        temp=(struct ListNode*)malloc(sizeof(struct ListNode));
        temp->val=p->val;
        temp->next=NULL;
        tail->next=temp;
        tail=temp;
        len++;
        if(p->next==NULL)break;
        p=p->next;
    }
    p->next=sentry->next;
    k=k%len,index=0;
    p=head;
    while(p){
        if(index==(len-k)){
            temp=p;
        }
        if(index==(2*len-k-1)){
            p->next=NULL;
            break;
        }
        index++;
        p=p->next;
    }
    return temp;
}

 

Rotate List || LeetCode

原文:http://www.cnblogs.com/ProtectedDream/p/4558823.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!