[关闭]
@snuffles 2019-04-10T18:35:52.000000Z 字数 853 阅读 793

L61 旋转链表

链表


给定一个链表,旋转链表,将链表每个节点向右移动 k 个位置,其中 k 是非负数。
示例 1:
输入: 1->2->3->4->5->NULL, k = 2
输出: 4->5->1->2->3->NULL
解释:
向右旋转 1 步: 5->1->2->3->4->NULL
向右旋转 2 步: 4->5->1->2->3->NULL

解:先获得链表长度,把链表头尾链接起来,往后走N-K%N个节点,到达新头结点前的一个点,断开链表。

  1. ListNode* rotateRight(ListNode* head, int k) {
  2. if(!head) return NULL;
  3. ListNode *cur = head;
  4. int count=0;
  5. while(cur->next){
  6. count ++;
  7. cur = cur->next;
  8. }
  9. count ++; //length
  10. cur->next = head;//link the head and tail;
  11. int move = count-k%count;
  12. ListNode *newhead = head,*newtail = head;
  13. while(move--){
  14. newhead = newhead->next;
  15. }
  16. move = count-k%count-1;
  17. while(move--){
  18. newtail = newtail->next;
  19. }
  20. newtail->next = NULL;
  21. return newhead;
  22. }
  1. ListNode* rotateRight(ListNode* head, int k) {
  2. if(head ==NULL || k==0) return head;
  3. ListNode *tail = head;
  4. int len=1;
  5. while(tail->next){
  6. tail=tail->next;
  7. len++;
  8. }
  9. tail->next = head;
  10. ListNode *newhead = head;
  11. int count=len-k%len;
  12. while(count--){
  13. newhead = newhead->next;
  14. tail = tail->next;
  15. }
  16. tail->next = NULL;
  17. return newhead;
  18. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注