【Leetcode】61. Rotate List - 循环链表

来源:互联网 发布:google 算法面试题 编辑:程序博客网 时间:2024/05/22 12:11

思路:
1. 遍历链表找到结尾,顺便统计链表长度count
2. 将结尾指向head,使链表首位相连,并计算前行长度count=count-k%count
3. 前行count步,当前指针为尾,next为new head

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     struct ListNode *next; * }; */struct ListNode* rotateRight(struct ListNode* head, int k) {    if (head==NULL||head->next==NULL){        return head;    }    struct ListNode *tail;    struct ListNode *p=head;    int count=1;    int newK;    while(p->next!=NULL){        p=p->next;        count++;    }    newK=k%count;    p->next=head;    count=count-newK;    p=head;    while(count-->1){        p=p->next;    }    tail=p;    head=p->next;    tail->next=NULL;    return head;}
0 0
原创粉丝点击