Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package linked_list_implementation;
- public class LinkedList<T> {
- private Node<T> head = null;
- void add(T element) {
- Node<T> node = new Node<>(element);
- if(head == null) {
- head = node;
- }
- else {
- Node<T> curr = head;
- while(curr.next != null) {
- curr = curr.next;
- }
- curr.next = node;
- }
- }
- void addFirst(T element) {
- Node<T> node = new Node<>(element);
- if(head == null) head = node;
- else{
- Node<T> curr = head;
- Node<T> res = node;
- while(curr != null) {
- node.next = curr;
- curr = curr.next;
- node = node.next;
- }
- head = res;
- }
- }
- T poll() {
- if(head == null) return null;
- Node<T> first = head;
- head = head.next;
- return first.val;
- }
- boolean remove(T element) {
- if(head == null) return false;
- if (head.next == null && head.val == element) {
- head = null;
- return true;
- }
- Node<T> curr = head;
- Node<T> prev = null;
- while(curr != null && curr.val != element) {
- prev = curr;
- curr = curr.next;
- }
- if (curr == null) return false;
- assert prev != null;
- prev.next = curr.next;
- return true;
- }
- @Override
- public String toString() {
- return "LinkedList{" +
- "head=" + head +
- '}';
- }
- private static class Node<T> {
- T val;
- Node<T> next;
- public Node(T val) {
- this.val = val;
- }
- public Node(T val, Node<T> next) {
- this.val = val;
- this.next = next;
- }
- @Override
- public String toString() {
- return "Node{" +
- "val=" + val +
- ", next=" + next +
- '}';
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement