题目
给你一个链表,每 k 个节点一组进行翻转,请你返回翻转后的链表。 k 是一个正整数,它的值小于或等于链表的长度。 如果节点总数不是 k 的整数倍,那么请将最后剩余的节点保持原有顺序。 给你这个链表:1->2->3->4->5 当 k = 2 时,应当返回: 2->1->4->3->5 当 k = 3 时,应当返回: 3->2->1->4->5
思路
代码
public ListNode
reverseKGroup(ListNode head
, int k
) {
if(head
==null
||head
.next
==null
) return head
;
ListNode tail
= head
;
for(int i
= 0;i
<k
;i
++){
if(tail
==null
) return head
;
tail
= tail
.next
;
}
ListNode prehead
= reverse(head
,tail
);
head
.next
= reverseKGroup
(tail
, k
);
return prehead
;
}
public ListNode
reverse(ListNode head
, ListNode tail
){
ListNode pre
= null
;
ListNode next
= null
;
while(head
!=tail
){
next
= head
.next
;
head
.next
= pre
;
pre
= head
;
head
= next
;
}
return pre
;
}
转载请注明原文地址:https://ipadbbs.8miu.com/read-13672.html