[LeetCode] Rotate List 單項鏈表旋轉

來源:互聯網
上載者:User

標籤:style   blog   http   io   ar   color   os   sp   for   

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.

 

Hide Tags Linked List Two Pointers     這題有點難理解,k 的意思是鏈表右起第k 個,k 大於鏈的個數時候,迴圈讀取,所以題目中k =5 的時候直接返回。思路是確定鏈表斷開的地方,有個技巧是一個快指標先遍曆k 次,然後快慢指標再一次遍曆,如果快指標到尾了,這時候慢指標後於快指標k 次,剛好是右起k 步。 
 1 #include <iostream> 2 using namespace std; 3  4 /** 5  * Definition for singly-linked list. 6  */ 7 struct ListNode { 8     int val; 9     ListNode *next;10     ListNode(int x) : val(x), next(NULL) {}11 };12 13 class Solution {14 public:15     ListNode *rotateRight(ListNode *head, int k) {16         if(head==NULL||k==0)  return head;17         int cnt =0;18         ListNode * first=head,*slow=head;19         while(cnt<k){20             if(first==NULL) first = head;21             first=first->next;22             cnt++;23         }24         if(first==NULL) return head;25         while(first->next!=NULL){26             first=first->next;27             slow=slow->next;28         }29         first->next=head;30         head = slow->next;31         slow->next = NULL;32         return head;33     }34 };35 36 int main()37 {38 39     return 0;40 }
View Code

 

[LeetCode] Rotate List 單項鏈表旋轉

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.