LeetCode-876 Middle of the Linked List Solution (with Java)

1. Description:

Notes: 

2. Examples:

3.Solutions:

 1 /**
 2  * Created by sheepcore on 2019-05-10
 3  * Definition for singly-linked list.
 4  * public class ListNode {
 5  *     int val;
 6  *     ListNode next;
 7  *     ListNode(int x) { val = x; }
 8  * }
 9  */
10 class Solution {
11     public ListNode middleNode(ListNode head) {
12         List<Integer> list = new ArrayList<>();
13         ListNode listNode = head;
14         listNode = head.next;
15 
16         int len = 0;
17         
18         while (listNode != null){
19             len++;
20             listNode = listNode.next;
21         }
22    
23         listNode = head;
24         if(len % 2 == 0){
25             for(int i = 0; i < len >> 1; i++){
26                 listNode = listNode.next;
27             }
28         } else{
29             for(int i = 0; i <= len >> 1; i++){
30                 listNode = listNode.next;
31             }     
32         }
33         return listNode;
34     }
35 }

 

 

posted @ 2020-03-02 15:02  SheepCore  阅读(145)  评论(0编辑  收藏  举报