add q25_k个一组翻转链表

pull/6/head
yuanguangxin 4 years ago
parent 4be6716c46
commit 12e58d63aa

@ -10,6 +10,7 @@
* [q2_两数相加](/src/链表操作/q2_两数相加)
* [q19_删除链表的倒数第N个节点](/src/链表操作/q19_删除链表的倒数第N个节点)
* [q25_k个一组翻转链表](/src/链表操作/q25_k个一组翻转链表)
* [q61_旋转链表](/src/链表操作/q61_旋转链表)
* [q138_复制带随机指针的链表](/src/链表操作/q138_复制带随机指针的链表)
* [q206_反转链表](/src/链表操作/q206_反转链表)

@ -0,0 +1,12 @@
package .q25_k;
public class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}

@ -0,0 +1,42 @@
package .q25_k;
public class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
ListNode hair = new ListNode(0);
hair.next = head;
ListNode pre = hair;
ListNode end = hair;
while (end.next != null) {
for (int i = 0; i < k && end != null; i++){
end = end.next;
}
if (end == null){
break;
}
ListNode start = pre.next;
ListNode next = end.next;
end.next = null;
pre.next = reverse(start);
start.next = next;
pre = start;
end = pre;
}
return hair.next;
}
private ListNode reverse(ListNode head) {
ListNode pre = null;
ListNode curr = head;
while (curr != null) {
ListNode next = curr.next;
curr.next = pre;
pre = curr;
curr = next;
}
return pre;
}
}
Loading…
Cancel
Save