标签:
Rotate List
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.
注意一点,K可能非常大,比链表的长度大得多,但是因为是循环右移,所以实际上只要循环右移K%Length位(Length为链表长度)。
//没理解好题意,写成了将右边k个数字移到前面,但是也能通过 //注意一点,K可能非常大,比链表的长度大得多,但是因为是循环右移,所以实际上只要循环右移K%Length位(Length为链表长度)。 class Solution { public: ListNode *rotateRight(ListNode *head, int k) { if(head==NULL) return head; int len = getlistlen(head); k = k%len; int n = len - k; if(k==0) return head; ListNode *first=head; for(int i=0; i<n-1; i++) { first = first->next; } ListNode *head2 = first->next; first->next = NULL; ListNode *second = head2; for(int i=0; i<k-1; i++) { second = second->next; } second->next = head; return head2; } private: int getlistlen( ListNode *head) { int len=0; while(head) { len++; head = head->next; } return len; } };
//另一种写法 class Solution { public: ListNode *rotateRight(ListNode *head, int k) { if (head == NULL || head->next == NULL || k == 0) { return head; } int length = 0; ListNode *ptr = head, *tail = head; while (ptr != NULL) { length++; tail = ptr; ptr = ptr->next; } k %= length; ptr = head; for (int i = 0; i < length - k - 1; i++) { ptr = ptr-> next; } tail->next = head; head = ptr->next; ptr->next = NULL; return head; } };
#include<iostream> using namespace std; #define N 5 struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; //没理解好题意,写成了将右边k个数字移到前面,但是也能通过 class Solution { public: ListNode *rotateRight(ListNode *head, int k) { if(head==NULL) return head; int len = getlistlen(head); k = k%len; int n = len - k; if(k==0) return head; ListNode *first=head; for(int i=0; i<n-1; i++) { first = first->next; } ListNode *head2 = first->next; first->next = NULL; ListNode *second = head2; for(int i=0; i<k-1; i++) { second = second->next; } second->next = head; return head2; } private: int getlistlen( ListNode *head) { int len=0; while(head) { len++; head = head->next; } return len; } }; ListNode *creatlist() { ListNode *head = NULL; ListNode *p; for(int i=0; i<N; i++) { int a; cin>>a; p = (ListNode*) malloc(sizeof(ListNode)); p->val = a; p->next = head; head = p; } return head; } int main() { ListNode *list = creatlist(); Solution lin; int a; cin>>a; ListNode *outlist = lin.rotateRight ( list,a ); for(int i=0; i<N; i++) { cout<<outlist->val; outlist = outlist->next; } }
标签:
原文地址:http://blog.csdn.net/keyyuanxin/article/details/43833381