LeetCode 876:链表的中间节点
题目:
代码示例:
package com.zy.leetcode.LeetCode_876;
/**
* @Author: zy
* @Date: 2024-12-27-15:41
* @Description:链表的中间节点
*/
public class ListNode {
private int val;
private ListNode next;
public ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
public ListNode() {
}
public ListNode(int val) {
this.val = val;
}
// 链表打印
private void print(ListNode node) {
while (node != null) {
System.out.print(node.val + " -> ");
node = node.next;
}
}
/**
* 找链表的中点
*
* @param head 头节点
* @param
*/
public static ListNode middleNode(ListNode head) {
ListNode slow = head, fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
/**
* 数组初始化链表
*/
public static ListNode initListNode(int[] arr) {
ListNode dummy = new ListNode(0);
ListNode cur = dummy;
for (int num : arr) {
cur.next = new ListNode(num);
cur = cur.next;
}
return dummy.next;
}
/**
* 获取链表的投节点并返回值
*/
private static int getHeadVal(ListNode node) {
if (node != null) {
return node.val;
}
return -1;
}
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5, 6};
ListNode head = initListNode(arr);
ListNode listNode = middleNode(head);
listNode.print(listNode); // 3 -> 4 -> 5 -> null
//System.out.println("----------------");
//int headVal = getHeadVal(listNode);
//System.out.println("HeadVal:" + headVal);
}
}