旋转链表
1、反转链表
1.1 问题
给你单链表的头节点
head
,请你反转链表,并返回反转后的链表。
1.2 代码
class Solution { public ListNode reverseList(ListNode head) { if(head == null || head.next == null) return head; ListNode last = reverseList(head.next); head.next.next = head; head.next = null; return last; } }
2、旋转部分链表
2.1 问题
给你单链表的头指针 head 和两个整数 left 和 right ,其中 left <= right 。请你反转从位置 left 到位置 right 的链表节点,返回 反转后的链表 。
2.2 代码
class Solution { public ListNode reverseBetween(ListNode head, int left, int right) { ListNode res = new ListNode(0); res.next = head; ListNode pre = res; ListNode post = head; for(int i = 0 ; i < left - 1; i++){ pre = pre.next; } for(int i = 0; i < right; i++){ post = post.next; } ListNode dummy = travers(pre.next,post); pre.next = dummy; return res.next; } public ListNode travers(ListNode head,ListNode post){ ListNode pre,cur,nxt; pre = post; cur = head; nxt = head; while(cur != post){ nxt = cur.next; cur.next = pre; pre = cur; cur = nxt; } return pre; } }
3、k组为一个进行旋转
3.1 问题
给你链表的头节点 head ,每 k 个节点一组进行翻转,请你返回修改后的链表。
k 是一个正整数,它的值小于或等于链表的长度。如果节点总数不是 k 的整数倍,那么请将最后剩余的节点保持原有顺序。
你不能只是单纯的改变节点内部的值,而是需要实际进行节点交换。
3.2 解题思路
首先抽取两个点:一个点是起始点,另一个点是结束点;
这一段点进行反转后,起始点的.next就是下一组的翻转,所以每一组反转的需要返回头节点作为返回值;
下一组反转就是本函数传入结束点的下一个,最终返回最新的head;
在对每一组进行反转时,反转的结束是当前cur==结束点;
定义pre、cur、nxt:
- pre初始为null;cur=nxt=起始点
- 因为nxt要指向pre,所以先对nxt进行保存
- pre变换为当前的cur、cur变换为下一个点
3.3 代码
class Solution { public ListNode reverseKGroup(ListNode head, int k) { ListNode post = head; ListNode pre = head; for(int i = 0; i < k; i++){ if(post == null) return pre; post = post.next; } ListNode root = reverseK(pre,post); pre.next = reverseKGroup(post,k); return root; } public ListNode reverseK(ListNode head,ListNode post){ ListNode cur,pre,nxt; pre = null; cur = head; nxt = head; while(cur != post){ nxt = cur.next; cur.next = pre; pre = cur; cur = nxt; } return pre; } }