码迷,mamicode.com
首页 > 其他好文 > 详细

Rotate List || LeetCode

时间:2015-06-07 18:49:46      阅读:136      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!