链表由多个节点node连接而成;
每个节点里面有val 和 下一节点地址
node.next = node1 //代表改变node的连接方向
node.next = new ListNode(1); //代表在node后面新加一个val为一的节点
ListNode run = new ListNode(0, head); //代表新建一个节点val为0 节点后面与head连接
ListNode pre = new ListNode(-1);
ListNode cur = pre;//新建一个val为-1节点 cur也指向pre的头节点
//可以用cur移动 最后return pre.next 代表最终结果
例题:
给你一个链表,每 k 个节点一组进行翻转,请你返回翻转后的链表。
k 是一个正整数,它的值小于或等于链表的长度。
如果节点总数不是 k 的整数倍,那么请将最后剩余的节点保持原有顺序
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-nodes-in-k-group
输入:head = [1,2,3,4,5], k = 2
输出:[2,1,4,3,5]
解题:代码:
public class leetcode_25 {
public ListNode reverseKGroup(ListNode head, int k) {
ListNode run = new ListNode(0, head);
ListNode pre = run;
ListNode end = run;
while (end.next != null) {
for (int i = 0; i < k && end != null; i++) {
end = end.next;
}
if (end == null) {
break;
}
ListNode start = pre.next;
ListNode bin = end.next;
//定义null来截断链表
end.next = null;
//反转
pre.next = reverse(start);
//接上反转后的链
start.next = bin;
pre = start;
end = pre;
}
return run.next;
}
//定义反转的方法
public ListNode reverse(ListNode head) {
ListNode pre = null;
ListNode cur = head;
while (cur != null) {
ListNode temp = cur.next;
cur.next = pre;
pre = cur;
cur = temp;
}
return pre;
}
}