题目描述
审题 很重要。。一开始以为是一组换两个,但是实际上是一组全部 都要互换。字节超高频题!要认真点记录
思路 & 代码
用回溯来做,可以分解成:每次都用head和之后的k-1个结点进行翻转操作,在翻转之前先把第k+1个结点传入下一个翻转函数,然后再翻转当前Head,并且连接上第k+1个结点。 题目不难,但是要注意考虑边界条件,还有由于链表性质导致的问题(指针丢失、弄混等)。
class Solution { public ListNode reverseKGroup ( ListNode head, int k) { if ( k == 1 ) { return head; } ListNode end = head; for ( int i= 0 ; i< k- 1 ; i++ ) { end = end. next; if ( end == null ) { return head; } } end = end. next; if ( end != null ) { end = reverseKGroup ( end, k) ; } ListNode first = head; ListNode nowNode = head. next; ListNode temp; for ( int i= 0 ; i < k- 1 ; i++ ) { temp = nowNode. next; nowNode. next = first; first = nowNode; if ( i != k- 2 ) { nowNode = temp; } } head. next = end; return nowNode; }
}
更新 - 精简版
class Solution { public ListNode reverseKGroup ( ListNode head, int k) { ListNode lastNode = head; for ( int i = 0 ; i < k - 1 ; i++ ) { lastNode = lastNode. next; if ( lastNode == null ) { return head; } } ListNode nextHead = null ; if ( lastNode. next != null ) { nextHead = reverseKGroup ( lastNode. next, k) ; } ListNode now = head, pre = null ; for ( int i = 0 ; i < k; i++ ) { ListNode temp = now. next; now. next = pre; pre = now; now = temp; } head. next = nextHead; return pre; }
}
三刷 - 再更新版
class Solution { public ListNode reverseKGroup ( ListNode head, int k) { if ( head == null ) return head; ListNode nowLast = head; for ( int i = 0 ; i < k - 1 ; i++ ) { if ( nowLast. next == null ) return head; nowLast = nowLast. next; } ListNode now = head, pre = reverseKGroup ( nowLast. next, k) ; while ( pre != nowLast) { ListNode temp = now. next; now. next = pre; pre = now; now = temp; } return nowLast; }
}