/* * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template */ package linkedlist; import java.util.LinkedList; /** * * @author chloe */ public class MyList { private Node head; class Node { E e; // Data than can be anything Node link; // Address of another node } public boolean add(E e) { Node newNode = new Node(); newNode.e = e; if (head == null) { head = newNode; } else { Node p = head; Node pTrail = head; while (p != null) { pTrail = p; p = p.link; } pTrail.link = newNode; } return true; } public boolean add(E e, int index) { Node newNode = new Node(); newNode.e = e;//copy data //Check index location if (index < 0 || index > size()) { throw new IndexOutOfBoundsException(); } //Case 1: list is empty and the index is zero if (size() == 0 && index == 0) { head = newNode; } //Case 2: Add at front else if (index == 0) { //Connect newNode with the first node newNode.link = head; //Make head point to new node head = newNode; } //Case 3: Add in middle else if (index < size()) { Node p = head; for (int i = 0; i < index - 1; ++i) { p = p.link;//advance the p } //Point link of new node to next node newNode.link = p.link; //make previous node link point to new node p.link = newNode; } //Case 4: Add at end of list else { add(e); } return true; } @Override public String toString() { String s = ""; Node p = head; while (p != null) { s += p.e.toString() + " "; p = p.link; } return "MyList{" + s + "}"; } public int size() { int count = 0; Node p = head; while (p != null) { ++count; p = p.link; } return count; } public E removeAt(int index) { if (size() == 0) { throw new EmptyListException("The list is empty."); } if (index < 0 || index >= size()) throw new IndexOutOfBoundsException(); if (size() == 0) throw new EmptyListException("Empty List"); E removedE = null; if (index == 0) { // remove the front removedE = head.e; Node p = head; head = head.link; p.link = null; } if (index > 0 && index < size()) { // remove middle Node p = head; for (int i = 0; i < index - 1; ++i) { p = head.link; } removedE = p.link.e; p.link = p.link.link; } else { // Remove at end Node p = head; for (int i = 0; i < index -1; ++i) { p = p.link; removedE = p.link.e; p.link = null; } } return removedE; } public static void main(String[] args) { LinkedList linkedList = new LinkedList<>(); MyList ml = new MyList<>(); ml.add(10); ml.add(20); ml.add(30); ml.add(5, 0); ml.add(25, 3); ml.add(40, 5); System.out.println("removing " + ml.removeAt(2) + "..."); System.out.println(ml); System.out.println(ml.size()); } }