1 找中点
笔者这几天在回顾链表的相关题目,发现快慢指针很好用,在做链表相关的题目时经常用到。比如今天有道题需要将链表从中间断开成两段,且前半段长度 >= 后半段长度。开始使用快慢指针的朴素写法(法1),发现需要在推出循环的时候根据链表的节点个数判断中点是那个以及从哪个节点进行断联操作,后来翻看做题记录发现法2更简洁(不用再判断从哪里断开链表),特此记录
- 法1:
// 从中间断开链表,并返回后半段的头节点
private ListNode getMid(ListNode head) {
ListNode slow = head, fast = head, prev = null;
while (fast != null && fast.next != null) {
prev = slow;
slow = slow.next;
fast = fast.next.next;
}
// 如果是奇数个节点,就从 curr 处断开;如果是偶数个节点,就从 prev 处断开
ListNode secondStart = null;
if (fast == null) {
secondStart = slow;
prev.next = null;
} else {
secondStart = slow.next;
slow.next = null;
}
return secondStart;
}
- 法2(推荐):
private ListNode findMiddle(ListNode head) {
if (head == null)
return head;
ListNode slow = head, fast = head;
while (fast != null) {
fast = fast.next;
if (fast == null) break;
fast = fast.next;
if (fast == null) break;
slow = slow.next;
}
return slow;
}