[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