25. Reverse Nodes in k-Group(java)__Java

來源:互聯網
上載者:User
Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.You may not alter the values in the nodes, only nodes itself may be changed.Only constant memory is allowed.For example,Given this linked list: 1->2->3->4->5For k = 2, you should return: 2->1->4->3->5For k = 3, you should return: 3->2->1->4->5

譯文:
給定一個鏈表,分別反轉鏈表的k個結點並返回修改後的鏈表。 如果鏈表的結點數量不是k的倍數,那麼你需要將餘下的結點保留在末尾; 你不能改變結點中的值,你只能改動結點的位置。

對於這道題,我已盡我所能卻沒有一絲的想法,後面去參考了別人的部落格,看了別人的想法才明白。心裏面不禁暗自的“誇獎”自己,原來我在演算法這塊兒這麼“強”。這道題主要可以用遞迴的思想去做,然後採用頭插法逆序建表。不瞭解頭插法建表的童鞋可以先去瞭解一下,之後再來做這道題目。下面附上改進後的代碼:

public class Solution{     public ListNode reverseKGroup(ListNode head, int k)     {         if(head == null)             return head;         if(head.next == null)             return head;         ListNode cur = head;         int count = 0;         while(cur != null && count != k)         {             cur = cur.next;             count++;         }         if(count == k)         {             cur = reverseKGroup(cur, k);             /*              * 使用頭插法建立逆序鏈表              */             while(--count >= 0)             {                 ListNode tmp = head.next;                 head.next = cur;                 cur = head;                 head = tmp;             }             head = cur;         }         return head;     }}

歡迎各位童鞋指出新的想法,我也可以學習學習各位大神的解答。附上執行結果,第一次遇見這樣的執行效果,心裡美滋滋的。哈哈。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.