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