LeetCode25 以k為一組,反轉連結串列
阿新 • • 發佈:2018-12-22
[LeetCode25] Reverse Nodes in k-Group 每k個一組翻轉連結串列
ven a linked list, reverse the nodes of a linked list k at a time and return its modified list.
k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.
Example:
Given this linked list: 1->2->3->4->5
For k = 2, you should return: 2->1->4->3->5
For k = 3, you should return: 3->2->1->4->5
Note:
Only constant extra memory is allowed.
You may not alter the values in the list’s nodes, only nodes itself may be changed.
費了好大勁,看懂了兩個解法(原諒渣渣我自己寫不出來),記錄如下。
C++
class Solution { public: ListNode* reverseKGroup(ListNode* head, int k) { ListNode *dummy = new ListNode(-1), *pre = dummy, *cur = pre; dummy->next = head; int num = 0; while (cur = cur->next) ++num; while (num >= k) { cur = pre->next; for (int i = 1; i < k; ++i) { ListNode *t = cur->next; cur->next = t->next; t->next = pre->next; pre->next = t; } pre = cur; num -= k; } return dummy->next; } };
Java
package src_Jiede1; import DataStructure.ListNode; import java.util.List; public class ReverseNodesinkGroup { public ListNode reverseKGroup(ListNode head, int k) { ListNode root = new ListNode(-1); root.next = head; ListNode res = root; ListNode temp = head; int i = 0; while(temp != null){ i++; temp = temp.next; } //i的最終結果就是連結串列中所有節點的總個數 while(i >= k){ for(int j = 0 ; j < k-1; j++){ //按上面分析中講的思路進行反轉連結串列的操作 ListNode node = root.next; //如果以k個結點為一組進行反轉,就要進行k-1次翻轉操作 System.out.println(node.val); System.out.println(node.val+","+head.val+","+root.val); root.next = head.next; //比如k=3,就是兩次操作:將2翻轉到1前面+將3翻轉到1前面 head.next = root.next.next; root.next.next = node; System.out.println(node.val+","+head.val+","+root.val); } //for迴圈裡面是一次翻轉操作 root = head; head = head.next; //以k為一組,就要將head移動到已經反轉過的結點後面繼續以k個結點為一組進行反轉 i-=k; //此時一共i個結點減去已經反轉過的k個結點得到剩餘節點個數 } return res.next; } public static void main(String[] args){ ReverseNodesinkGroup a=new ReverseNodesinkGroup(); ListNode l=new ListNode(1); l.next=new ListNode(2); l.next.next= new ListNode(3); l.next.next.next=new ListNode(4); l.next.next.next.next=new ListNode(5); a.reverseKGroup(l,3); } }
參考部落格:
https://www.cnblogs.com/grandyang/p/4441324.html
https://blog.csdn.net/tzyshiwolaogongya/article/details/79889012