项目作者: eMahtab

项目描述 :
Find the middle node of the Linked List
高级语言:
项目地址: git://github.com/eMahtab/middle-of-the-linked-list.git
创建时间: 2020-02-09T16:05:00Z
项目社区:https://github.com/eMahtab/middle-of-the-linked-list

开源协议:

下载


Middle of the Linked List

https://leetcode.com/problems/middle-of-the-linked-list

Given a non-empty, singly linked list with head node head, return a middle node of linked list.

If there are two middle nodes, return the second middle node.

  1. Example 1:
  2. Input: [1,2,3,4,5]
  3. Output: Node 3 from this list (Serialization: [3,4,5])
  4. The returned node has value 3. (The judge's serialization of this node is [3,4,5]).
  5. Note that we returned a ListNode object ans, such that:
  6. ans.val = 3, ans.next.val = 4, ans.next.next.val = 5, and ans.next.next.next = NULL.
  7. Example 2:
  8. Input: [1,2,3,4,5,6]
  9. Output: Node 4 from this list (Serialization: [4,5,6])
  10. Since the list has two middle nodes with values 3 and 4, we return the second one.

Middle of the Linked List

Note:

The number of nodes in the given list will be between 1 and 100

Implementation 1 : First calculate size of list

  1. /**
  2. * Definition for singly-linked list.
  3. * public class ListNode {
  4. * int val;
  5. * ListNode next;
  6. * ListNode(int x) { val = x; }
  7. * }
  8. */
  9. class Solution {
  10. public ListNode middleNode(ListNode head) {
  11. if(head == null)
  12. return null;
  13. int size = 0;
  14. ListNode current = head;
  15. while(current != null) {
  16. size++;
  17. current = current.next;
  18. }
  19. current = head;
  20. for(int i = 1; i <= size / 2; i++){
  21. current = current.next;
  22. }
  23. return current;
  24. }
  25. }

Implementation 2 : Fast and Slow Pointer

When traversing the list with a pointer slow, make another pointer fast that traverses twice as fast.
When fast reaches the end of the list, slow must be in the middle.

  1. /**
  2. * Definition for singly-linked list.
  3. * public class ListNode {
  4. * int val;
  5. * ListNode next;
  6. * ListNode() {}
  7. * ListNode(int val) { this.val = val; }
  8. * ListNode(int val, ListNode next) { this.val = val; this.next = next; }
  9. * }
  10. */
  11. class Solution {
  12. public ListNode middleNode(ListNode head) {
  13. if(head == null)
  14. return head;
  15. ListNode slow = head;
  16. ListNode fast = head;
  17. while(fast != null && fast.next != null) {
  18. slow = slow.next;
  19. fast = fast.next.next;
  20. }
  21. return slow;
  22. }
  23. }

Complexity Analysis :

  1. Time Complexity: O(N), where NN is the number of nodes in the given list.
  2. Space Complexity: O(1), the space used by slow and fast.