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个结点。主要是考察对链表指针的熟悉程度。
1.计算链表的长度以及记录链表的尾指针,同时k%=lenght;
2.找出从尾部数第k个结点,然后该表链表的指向;
/** * 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==NULL||head->next==NULL||k==0) return head; int length=0; ListNode *pCur=head; ListNode *pTail=head; while(pCur!=NULL) { length++; pTail=pCur; pCur=pCur->next; } k%=length; pCur=head; for(int i=0;i<length-k-1;i++) pCur=pCur->next; pTail->next=head; head=pCur->next; pCur->next=NULL; return head; } };
原文:http://www.cnblogs.com/awy-blog/p/3750091.html