描述
将给出的链表中的节点每 k 个一组翻转,返回翻转后的链表
如果链表中的节点数不是 k 的倍数,将最后剩下的节点保持原样
你不能更改节点中的值,只能更改节点本身。
题解:链表的翻转可以使用栈这个结构,化解引用复杂变化的问题。
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* }
*/
public class Solution {
/**
*
* @param head ListNode类
* @param k int整型
* @return ListNode类
*/
public ListNode reverseKGroup (ListNode head, int k) {
// write code here
if(head==null) return head;
Stack<ListNode> nodestack=new Stack<>();
ListNode pre=new ListNode(-1);
ListNode temp=pre;
int i=0;
int count=0;
while(true)
{
for(int j=0;j<k;j++)
{
count++;
nodestack.push(head);
head=head.next;
if(head==null) break;
}
if(count!=k){
break;
}
for(int j=0;j<k;j++)
{
pre.next=nodestack.pop();
pre=pre.next;
pre.next=null;
}
if(head==null) break;
count=0;
}
ListNode end=null;
while(!nodestack.isEmpty()){
end=nodestack.pop();
}
pre.next=end;
return temp.next;
}
}