leetcode---rotate-list---链表

来源:互联网 发布:单片机一键信号发射 编辑:程序博客网 时间:2024/06/05 00:26

Given a list, rotate the list to the right by k places, where k is non-negative.
For example:
Given1->2->3->4->5->NULLand k =2,
return4->5->1->2->3->NULL.

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    ListNode *reverse(ListNode *head)    {        if(!head || !head->next)            return head;        ListNode *nextH = head->next;        ListNode *newH = reverse(nextH);        nextH->next = head;        head->next = NULL;        return newH;    }    ListNode *rotateRight(ListNode *head, int k)     {        if(!head || k == 0)            return head;        int n = 0;        ListNode *p = head;        ListNode *last = head;        while(p)        {            n++;            last = p;            p = p->next;        }        k = k % n;        if(k == 0)            return head;        n = n - k;        int i = 1;        p = head;        while(p && i<n)        {            i++;            p = p->next;        }        ListNode *next = p->next;        p->next = NULL;        last->next = head;        return next;    }};
原创粉丝点击