本文主要是介绍力扣876.链表的中间节点,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
876.链表的中间节点
思路1(数组):
- 新建 ListNode 数组存放 节点
- 根据节点个数 t ,返回 ListNode 的 t/2
代码实现
/*** Definition for singly-linked list.* public class ListNode {* int val;* ListNode next;* ListNode() {}* ListNode(int val) { this.val = val; }* ListNode(int val, ListNode next) { this.val = val; this.next = next; }* }*/
class Solution {public ListNode middleNode(ListNode head) {ListNode[] A = new ListNode[100];int t = 0;while (head!= null) {A[t++] = head;head = head.next;}return A[t/2];}
}
思路2(单指针法):
- 先通过循环一边链表,得出节点个数
- 根据节点个数 除以 2 得到链表返回
代码实现
/*** Definition for singly-linked list.* public class ListNode {* int val;* ListNode next;* ListNode() {}* ListNode(int val) { this.val = val; }* ListNode(int val, ListNode next) { this.val = val; this.next = next; }* }*/
class Solution {public ListNode middleNode(ListNode head) {int n = 0;ListNode cur = head;while (cur != null) {n++;cur = cur.next;}cur = head;int k = 0;while (k < (n/2)) {k++;cur = cur.next;}return cur;}
}
思路3(快慢指针):
只要从同一时间同一地点出发,当快指针走到末尾时,慢指针一定走到中间
- 创建 快慢指针 同时指向 head
- 使用while循环,slow走一步,fast走两步,找判断条件
- 返回 slow
注意:
while (fast != null && fast.next != null ) 条件顺序一定不能反,否则会导致越界
代码实现
/*** Definition for singly-linked list.* public class ListNode {* int val;* ListNode next;* ListNode() {}* ListNode(int val) { this.val = val; }* ListNode(int val, ListNode next) { this.val = val; this.next = next; }* }*/
class Solution {public ListNode middleNode(ListNode head) {ListNode slow = head;ListNode fast = head;while (fast != null && fast.next != null ) {slow = slow.next;fast = fast.next.next;}return slow;}
}
这篇关于力扣876.链表的中间节点的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!