LeetCode第25题:K个一组反转链表
题目:给你一个链表,每 k 个节点一组进行翻转,请你返回翻转后的链表。 解法一:这个方法是自己做的错方法,我希望可以通过循环K次,每一次都把后以为加到head的前面。改了好长时间也没改对。。。。放弃。。。。
class Solution {
public ListNode reverseKGroup ( ListNode head, int k) {
if ( head == null ) {
return head;
}
int count = k- 1 ;
ListNode startNode = head, stopNode = head;
while ( stopNode. next!= null && count!= 0 ) {
stopNode = stopNode. next;
count-- ;
}
if ( count!= 0 )
return head;
ListNode next = head. next;
ListNode headt = head;
ListNode Lnext= next. next;
for ( int i= 0 ; i< k- 1 ; i++ ) {
Lnext = next. next;
head. next= Lnext;
next. next= headt;
headt= next;
next= Lnext;
}
head. next = reverseKGroup ( Lnext, k) ;
return next;
}
}
public ListNode reverseKGroup ( ListNode head, int k) {
if ( head== null)
return head;
int count = k- 1 ;
ListNode startNode = head, stopNode = head;
while ( stopNode. next!= null && count!= 0 ) {
stopNode = stopNode. next;
count-- ;
}
if ( count!= 0 )
return head;
ListNode next = stopNode. next;
stopNode = reverse ( startNode, stopNode) ;
startNode. next = reverseKGroup ( next, k) ;
return stopNode;
}
ListNode reverse ( ListNode startNode, ListNode stopNode) {
ListNode pre = null, cur = startNode, stop = stopNode. next;
while ( cur!= stop) {
ListNode temp = cur. next;
cur. next = pre;
pre = cur;
cur = temp;
}
return pre;
}
作者:bzdgz
链接:https: / / leetcode- cn. com/ problems/ reverse- nodes- in- k- group/ solution/ javashi- jian- ji- bai- 100 nei- cun- 96 - by- bzdgz/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。