61. Rotate List(unsolved)

来源:互联网 发布:java获取request对象 编辑:程序博客网 时间:2024/06/05 23:54

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.

解答:
本来是想用一个先走再走另一个的,但是好像不行。就按照这样做吧

/** * 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;       int len=1;       ListNode* tail=head,*newhead=head;       while(tail->next)       {           tail=tail->next;           len++;       }       tail->next=head;       if(k%=len)       {           for(auto i=0;i<len-k;i++) tail=tail->next;       }       newhead=tail->next;       tail->next=NULL ;       return newhead;    }};
0 0
原创粉丝点击