【LeetCode】第17天 - 25. K 个一组翻转链表
发布时间:2022-12-26 16:50:26 282 相关标签:
25. K 个一组翻转链表
- 题目描述
- 解题思路
- 代码实现
题目描述


解题思路
- 首先我们需要直到如何翻转一个链表
- 然后从头结点开始遍历链表,将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; }
* }
*/
class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
ListNode newHead = new ListNode(0); //新链表的头
newHead.next = head;
ListNode tempHead = newHead; // 子链表的头
ListNode tail = newHead; //子链表的尾
while(head != null){
for(int i=0;i<k;i++){
tail = tail.next; //head~tail表示一个子链表
if(tail == null){ //最后不足k个节点时直接返回
return newHead.next;
}
}
ListNode next = tail.next;
ListNode[] reverse = reverse(head, tail); //翻转子链表
head = reverse[0];
tail = reverse[1];
// 把子链表重新接回新链表
tempHead.next = head;
tail.next = next;
tempHead = tail;
head = tail.next;
}
return newHead.next;
}
//翻转head~tail的链表
public ListNode[] reverse(ListNode head, ListNode tail) {
ListNode prev = tail.next;
ListNode p = head;
while (prev != tail) {
ListNode nex = p.next;
p.next = prev;
prev = p;
p = nex;
}
return new ListNode[]{tail, head};
}
}
文章来源: https://blog.51cto.com/u_15901218/5914689
特别声明:以上内容(图片及文字)均为互联网收集或者用户上传发布,本站仅提供信息存储服务!如有侵权或有涉及法律问题请联系我们。
举报