题解 | #链表中的节点每k个一组翻转#
链表中的节点每k个一组翻转
https://www.nowcoder.com/practice/b49c3dc907814e9bbfa8437c251b028e
此题使用递归方法较为简单,解题思路如下
首先,创建头结点和前置空节点,并创建cur后节点CurNext
public ListNode reverse(ListNode head, int k) {
ListNode pre = null;
ListNode cur = head;
int count = 0;
ListNode CurNext = null;
int a=len(head);
其次,在创立函数len来计算链表长度k
public int len(ListNode head) {
ListNode cur = head;
int count = 0;
if (cur==null) {
return 0;
}
while (cur!=null){
cur=cur.next;
count++;
}
return count;
}
排除所分大小比链表长度大的情况
if (a<k){ return head; }创立条件,反转链表区间的值,并将这个区间的尾节点的next设置为下个区间的头结点,形成递归
while (count < k && cur != null) {
CurNext = cur.next;
cur.next = pre;
pre = cur;
cur = CurNext;
count++;
}
if (CurNext != null) {
head.next = reverse(CurNext, k);
}
return pre;
}
如上
