BAEL-1773 Find the middle element of a Linked List. (#4425)
* BAEL-1773 - find middle element of linked list * changes from review * changes from review * find middle element in linked list * typo
This commit is contained in:
committed by
Predrag Maric
parent
8080f07c6c
commit
0a3d212a2a
@@ -1,10 +1,20 @@
|
||||
package com.baeldung.linkedlist;
|
||||
|
||||
import com.baeldung.linkedlist.LinkedList.Node;
|
||||
import java.util.LinkedList;
|
||||
|
||||
import com.baeldung.linkedlist.Node;
|
||||
|
||||
public class MiddleElementLookup {
|
||||
|
||||
public static String findMiddleElement(Node head) {
|
||||
public static String findMiddleElementLinkedList(LinkedList<String> linkedList) {
|
||||
if (linkedList == null || linkedList.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return linkedList.get((linkedList.size() - 1) / 2);
|
||||
}
|
||||
|
||||
public static String findMiddleElementFromHead(Node head) {
|
||||
if (head == null) {
|
||||
return null;
|
||||
}
|
||||
@@ -26,7 +36,7 @@ public class MiddleElementLookup {
|
||||
return current.data();
|
||||
}
|
||||
|
||||
public static String findMiddleElement1PassRecursively(Node head) {
|
||||
public static String findMiddleElementFromHead1PassRecursively(Node head) {
|
||||
if (head == null) {
|
||||
return null;
|
||||
}
|
||||
@@ -53,7 +63,7 @@ public class MiddleElementLookup {
|
||||
middleAux.length--;
|
||||
}
|
||||
|
||||
public static String findMiddleElement1PassIteratively(Node head) {
|
||||
public static String findMiddleElementFromHead1PassIteratively(Node head) {
|
||||
if (head == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
34
core-java/src/main/java/com/baeldung/linkedlist/Node.java
Normal file
34
core-java/src/main/java/com/baeldung/linkedlist/Node.java
Normal file
@@ -0,0 +1,34 @@
|
||||
package com.baeldung.linkedlist;
|
||||
|
||||
public class Node {
|
||||
private Node next;
|
||||
private String data;
|
||||
|
||||
public Node(String data) {
|
||||
this.data = data;
|
||||
}
|
||||
|
||||
public String data() {
|
||||
return data;
|
||||
}
|
||||
|
||||
public void setData(String data) {
|
||||
this.data = data;
|
||||
}
|
||||
|
||||
public boolean hasNext() {
|
||||
return next != null;
|
||||
}
|
||||
|
||||
public Node next() {
|
||||
return next;
|
||||
}
|
||||
|
||||
public void setNext(Node next) {
|
||||
this.next = next;
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
return this.data;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user