反转链表的进阶版。
题目描述
给出一个链表,每 k 个节点一组进行翻转,并返回翻转后的链表。k 是一个正整数,它的值小于或等于链表的长度。如果节点总数不是 k 的整数倍,那么将最后剩余节点保持原有顺序。
public static ListNode ReverseList(ListNode head,int k) { if(head==null||head.next==null || k<2){ return head; } ListNode currentNode = head; for (int i = 1; i < k ; i++) { currentNode=currentNode.next; if(currentNode==null){ return head; } } ListNode next=currentNode.next; reverse(head,currentNode); //反转核心算法 head.next=ReverseList(next,k); //将链表分段反转之后连接 return currentNode; } //与反转链表中的核心算法一致, 不同的是控制转换的范围不一样。反转链表是判断结点是否为空然后反转,这里是判断到相应的结束节点 public static ListNode reverse(ListNode head,ListNode endNode) { if(head==null || head.next==null){ return head; } ListNode pre=null; ListNode next=null; while(pre!=endNode){ next=head.next; head.next=pre; pre=head; head=next; } return pre; }