diff --git a/Java/LinkedList/Intro.java b/Java/LinkedList/Intro.java new file mode 100644 index 00000000..e3025210 --- /dev/null +++ b/Java/LinkedList/Intro.java @@ -0,0 +1,15 @@ +package Ds.LinkedList; +import java.util.*; +public class Intro { + + public static void main(String[] args) { + + MyLinkedList myLL = new MyLinkedList(); + + for (int i=0; i<10;i++) { + myLL.add(i+" hemlo"); + } + myLL.print(); + + } +} diff --git a/Java/LinkedList/MyLinkedList.java b/Java/LinkedList/MyLinkedList.java new file mode 100644 index 00000000..bc614252 --- /dev/null +++ b/Java/LinkedList/MyLinkedList.java @@ -0,0 +1,74 @@ +package Ds.LinkedList; + +public class MyLinkedList { + + Node head; + public void add(E data) { + Node toAdd = new Node(data); + + if(isEmpty()) { + head = toAdd; + return; + } + Node temp = head; + while (temp.next != null) { + temp = temp.next; + } + temp.next = toAdd; + } + void print() { + Node temp = head; + while (temp != null) { + System.out.print(temp.data+" "); + temp = temp.next; + } + } + public E removeLast() throws Exception { + Node temp = head; + if(temp==null) { + throw new Exception ("no element"); + } + if(temp.next==null) { + Node toRemove = head; + head= null; + return (E) toRemove.data; + } + + while (temp.next.next != null) { + temp = temp.next; + } + Node toRemove = temp.next; + temp.next=null; + return (E) toRemove.data; + } + + public boolean isEmpty(){ + if(head==null) { + return true; + }else { + return false; + } + } + public E getLast() throws Exception{ + Node temp = head; + if(temp==null) { + throw new Exception ("cannot peek no element"); + } + while (temp.next != null) { + temp = temp.next; + } + + return temp.data; + } + + public static class Node { + public E data; + public Node next; + + public Node (E data) { + this.data = data; + next = null; + } + } + +}