LinkedList
必须熟练无脑敲出来的功能:
1. 链表反转:
public ListNode reverseList(ListNode head){
ListNode pre = null;
while(head != null){
ListNode tmp = head.next;
head.next = pre;
pre = head;
head = tmp;
}
return pre;
}
// 递归写法, 进入下一层之前存.next, 用来连接, 返回newHead public ListNode reverseList(ListNode head){ if(head == null || head.next == null){ return head; } ListNode nextNode = head.next; ListNode newHead = reverseList(head.next); nextNode.next = head; head.next = null; return newHead; }
2. 找链表中点
private TreeNode findPreMid(ListNode head){ ListNode slow = head; ListNode fast = head; while(fast != null && fast.next != null){ slow = slow.next; fast = fast.next.next; } return slow; }
a. 快慢指针都是head, 条件fast != null && fast.next != null
奇数个:slow 在中点, fast 在tail
偶数个: slow 在后一半第一个, fast在null
b. 如果 fast.next != null && fast.next.next != null
奇数个:slow在中点, fast在倒数第二个
偶数个:slow 在前一半最后一个,fast在tail
如果是找中点前一个 就用一个pre跟着slow:
private ListNode findPreMid(ListNode head){ ListNode slow = head; ListNode fast = head; ListNode pre = head; while(fast != null && fast.next != null){ pre = slow; slow = slow.next; fast = fast.next.next; } return pre; }
浙公网安备 33010602011771号