目录
链表中的节点每k个一组翻转
题目描述
将给出的链表中的节点每 k 个一组翻转,返回翻转后的链表
如果链表中的节点数不是 k 的倍数,将最后剩下的节点保持原样
你不能更改节点中的值,只能更改节点本身。要求空间复杂度O(1)
例如:给定的链表是 1→2→3→4→5
对于 k=2,你应该返回 2→1→4→3→5
对于 k=3,你应该返回 3→2→1→4→5
示例1
输入
{1,2,3,4,5},2
返回值
{2,1,4,3,5}
方法一:栈
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
Stack<Integer> stack=new Stack();
ListNode res=head;
while(head!=null){
ListNode node=head;
for (int i = 0; i < k; i++) {
if(node!=null){
stack.push(node.val);
node=node.next;
}else{
return res;
}
}
int size=stack.size();
for (int i = 0; i < size; i++) {
head.val=stack.pop();
head=head.next;
}
}
return res;
}
}
方法二:递归
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||head.next==null) return head;
ListNode h=new ListNode(0);
h.next=head;
ListNode next=null,tmp=head,cur=head;
for(int i=1;i<k;i++){//如果个数小于k,则不翻转
cur=cur.next;
if(cur==null)
return head;
}
next=cur.next;//终止的节点
while(head.next!=next){//循环k次
tmp=head.next;
head.next=tmp.next;
tmp.next=h.next;
h.next=tmp;
}
head.next=reverseKGroup(next,k);//递归翻转后续的链表
return h.next;
}
}