解题思路
//1,创建hashmap,key为i自增,value为node
//2,取得i中间值 map.get()获取中间node返回
这个算法遍历一次,获取len。取值不需要遍历
执行结果
执行用时:0 ms, 在所有 Java 提交中击败了100.00%的用户
内存消耗:38.9 MB, 在所有 Java 提交中击败了76.64%的用户
代码
/**
* 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) {
//1,创建hashmap,i-head.val
//2,取得中间数 get hashmap
HashMap<Integer, ListNode> map = new HashMap<Integer,ListNode>();
int i =1;
map.put(i,head);
while (head.next!=null){
map.put(++i,head.next);
head=head.next;
}
int k =1+i/2;
return map.get(k);
}
}