通过做以上的Leetcode练习题目,得出以下比较通用的解题方法:
快慢指针求链表中点
ListNode slow = head;
ListNode fast = head;
while (fast.next != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
// 此时slow指针所指的节点就是链表的中点
// 注意:当节点数为偶数是,slow指向的是靠左的节点
反转链表
ListNode prev = null;
ListNode next = null;
while (head != null) {
next = head.next;
head.next = prev;
prev = head;
head = next;
}
// 双指针即可 结合给出链表的head头节点
遍历链表时增加一个假头节点
ListNode new_list = new ListNode(-1);
ListNode p = new_list, sentry = head;
快慢指针找出环形链表的交点
ListNode slow = head, fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
// 当快慢指针第一次相遇时,放慢快指针速度,重置slow到头节点
if (slow == fast) {
slow = head;
while (slow != fast) {
fast = fast.next;
slow = slow.next;
}
// 第二次相遇,此时slow指针就指向交点
return slow;
}
}
注意:while循环条件一般为都:
while (fast != null && fast.next != null)