题目
25. K 个一组翻转链表
https://leetcode-cn.com/problems/reverse-nodes-in-k-group/
题解
我的指针的做法
我是喜欢用迭代来进行翻转的所以我这里还是用了迭代的思想。
先找到需要反转的链表,然后翻转,然后在进行拼接。看起来很简单,我们我们先遍历需要反转的链表段子,也就是先走过k个ListNode
。然后用几个变量先记录下当前的链表的情况。
reverse(start,end) 表示翻转start到end的链表,并且返回反转后的头结点。
public ListNode reverseKGroup(ListNode head, int k) {
if (head == null || head.next == null) {
return head;
}
ListNode dummy= new ListNode(0);
ListNode pre = dummy;
ListNode cur = head;
pre.next = cur;
ListNode start = null;
ListNode end = null;
ListNode after = null;
while (cur != null) {
boolean isEnd = false;
start = cur;
for (int i = 0; i < k-1; i++) {
if (cur == null) {
isEnd = true;
break;
}
cur = cur.next;
}
if (isEnd || cur == null) {
break;
}
end = cur;
after = cur.next;
pre.next = reserve(start, end);
start.next = after;
pre = start;
cur = after;
}
return dummy.next;
}
// 反转链表
private ListNode reserve(ListNode start, ListNode end) {
ListNode pre = null;
ListNode current = start;
ListNode after = null;
while (pre != end && current != null) {
after = current.next;
current.next = pre;
pre = current;
current = after;
}
return end;
}
栈
用栈的思想就很简单了,但是应该是不符合的题目的不能用额外的空间这个条件
public ListNode reverseKGroup(ListNode head, int k) {
if (head == null || head.next == null) {
return head;
}
Stack<ListNode> stack = new Stack<>();
boolean isFirst = true;
ListNode dummyNode = new ListNode(0);
ListNode pre = dummyNode;
while (true) {
int count = 0;
ListNode temp = head;
// 开始填栈,要么到了尾结点,要么栈的元素的数量等于k
while (temp != null && count < k) {
stack.push(temp);
temp = temp.next;
count++;
}
// 到了尾结点了。
if (count < k) {
pre.next = head;
break;
}
// 根据栈里的元素进行反转
while (!stack.isEmpty()) {
pre.next = stack.pop();
pre = pre.next;
}
// 为了防止下一个没满足反转的条件,直接退出的情况
pre.next = temp;
head = temp;
}
return dummyNode.next;
}