数据结构知识
链接:K 个一组翻转链表
算法思路
- 思路回忆:简单反转链表,记得保存节点就好。
- 由此,代码模板如下:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
public class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
ListNode preHead= new ListNode() ,afterTail,realHead;
realHead = preHead;
preHead.next = head;
int i = 1;
while(head!=null){
if(i%k==0){
afterTail = head.next;
ListNode[] nodes = reverseList(preHead.next,head);
preHead.next = nodes[0];
nodes[1].next = afterTail;
preHead = nodes[1];
head = afterTail;
i=1;
}else{
i++;
head = head.next;
}
}
return realHead.next;
}
// 反转链表,需要返回反转后得到头节点和尾节点
public ListNode[] reverseList(ListNode head,ListNode tail){
ListNode pre = null;
ListNode tempHead = head;
while(head!=tail){
ListNode temp = head.next;
head.next = pre;
pre = head;
head = temp;
}
tail.next = pre;
pre = tail;
ListNode[] nodes = new ListNode[2];
nodes[0] = pre; //左端点
nodes[1] = tempHead; //右端点
return new ListNode[](pre,tempHead);
}
}