Regarding finding the middle element of linked list

后端 未结 5 1624
轮回少年
轮回少年 2021-02-04 20:19

I am following the below approach to calculate the middle element from the linked list , but I want is there any built in method or any other approach which can als

相关标签:
5条回答
  • 2021-02-04 20:49

    Options:

    • Have a double linked-list and go from the back and front at the same time until you get to a common point.
    • Store the size of the list and simply stop when you've reached this half this size (similar to what the standard API's LinkedList does).

    Other than that I don't think you can do better than your algorithm.

    0 讨论(0)
  • 2021-02-04 20:51

    The basic algorithm would be

    • Take two pointers

    • Make both pointing to first node

    • Increment first with two nodes and second with one, at a time.

    • Loop until the 1st loop reaches the end. At this point, the 2nd will be at the middle.

    Example:-

    while ( p2.next != null ) {
        p2 = p2.next;
        if (p2.next != null) {
            p2 = p2.next;
            p1 = p1.next;
        }
    }
    

    It will definitely work in odd case, for even case you need to check one more condition if first point is allowed to move next but not next to next then both pointers will be at middle you need to decide which to take as middle.

    0 讨论(0)
  • 2021-02-04 20:58
    public Node getMiddleElement(Node head) {
        Node slow_pointer=head;
        Node fast_pointer=head;
        while(fast_pointer.next!=null && fast_pointer.next.next!=null)
        {
            slow_pointer=slow_pointer.next;
            fast_pointer=fast_pointer.next.next;
        }
        return slow_pointer;
    }
    
    Node mid_elem=PrintMiddleElement(head);
    System.out.println(mid_elem.data);
    

    I/P:5 10 15 25 35 25 40 O/P:25

    0 讨论(0)
  • 2021-02-04 21:03

    Solution for this question:

    • Use two indexes, first and second, both initialized to 0
    • Increment first by 1 and second by 2 * first
    • Set value of first to middle
    • Loop will execute until value of second is less than list size

    Here is code snippet for getting middle element of list or linked list:

    private int getMiddle(LinkedList<String> list) {
    
       int middle = 0;
       int size = list.size();
    
       for (int i = 0, j = 0; j < size; j = i * 2) {
           middle = i++;
       }
    
       return middle;
    }
    
    LinkedList<String> list = new LinkedList<>();
    list.add("1");
    list.add("2");
    list.add("3");
    list.add("4");
    list.add("5");
    list.add("6");
    list.add("7");
    int middle = getMiddle(list);
    System.out.println(list.get(middle));
    
    0 讨论(0)
  • 2021-02-04 21:05

    I would recommend using the Java built in

    LinkedList<Object e>
    

    It gives you all the functionality you need like getting the length: list.size(), and the middle object:

    list.get((list.size())/2);
    
    0 讨论(0)
提交回复
热议问题