package com.lxg.algorithm;
/**
* 给定一个带有头结点 head 的非空单链表,返回链表的中间结点。
* 如果有两个中间结点,则返回第二个中间结点。
*/
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}
public class Solution04 {
/**
* @param head: the head node
* @return: the middle node
*/
public static ListNode middleNode(ListNode head) {
// write your code here.
if (head.next == null) {
return head;
}
ListNode temp = head;
int length = 0;
while (temp != null) {
temp = temp.next;
length++;
}
int mid = length/2;
temp = head;
System.out.println("mid = " + mid);
while (mid-->0) {
temp = temp.next;
}
System.out.println("length = " + length);
return temp;
}
public static void main(String[] args) {
ListNode head = new ListNode(0);
ListNode L1 = new ListNode(1);
ListNode L2 = new ListNode(2);
ListNode L3 = new ListNode(3);
ListNode L4 = new ListNode(4);
ListNode L5 = new ListNode(5);
head.next = L1;
L1.next = L2;
L2.next = L3;
L3.next = L4;
// L4.next = null;
L4.next = L5;
L5.next = null;
ListNode temp = middleNode(head);
while (temp != null) {
System.out.println(temp.val);
temp = temp.next;
}
}
}
1609. 链表的中间结点
最新推荐文章于 2022-05-15 17:32:11 发布