* class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * }
查找一个链表的中间节点:使用快慢指针
注意:如果用途是对链表的左右分别递归调用时,需要将中间节点的前一个结点的next = null 即需要一个pre结点(注意先要赋null初始化)
ListNode midList(ListNode node){ if(node == null || node.next == null) return node; ListNode slow = node, fast = node; ListNode pre = null; while(fast != null && fast.next != null){ pre = slow; slow = slow.next; fast = fast.next.next; } pre.next = null; return slow; }
反转一个链表,并返回头结点
ListNode reverse(ListNode node){ if(node == null || node.next == null) return node; ListNode pre = null; while(node != null){ ListNode next = node.next; node.next = pre; pre = node; node = next; } return pre; }
原文地址:https://www.cnblogs.com/SkyeAngel/p/9284991.html
时间: 2024-11-08 21:45:13