Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Iterator;
- import java.util.NoSuchElementException;
- public class LinkedList<T> implements Iterable<T>{
- private ListNode<T> front;
- private int size = 0;
- public LinkedList(){
- front = null;
- }
- public void add(T obj){
- ListNode<T> node = new ListNode<T>(obj, null);
- ListNode<T> curr;
- if(front == null){
- front = node;
- }
- else{
- curr = front;
- while(curr.getNext() != null){
- curr = curr.getNext();
- }
- curr.setNext(node);
- }
- size++;
- }
- public void add(int index, T obj){
- if(index == 0){
- addFirst(obj);
- }
- else{
- ListNode<T> node = new ListNode<T>(obj, null);
- ListNode<T> curr = front;
- int c = 0;
- while(c + 1 != index && curr.getNext() != null){
- curr = curr.getNext();
- c++;
- }
- ListNode<T> next = curr.getNext();
- curr.setNext(node);
- node.setNext(next);
- size++;
- }
- }
- public void addFirst(T obj){
- front = new ListNode<T>(obj, front);
- }
- public T get(int index){
- if(front == null){
- return null;
- }
- else{
- ListNode<T> cNode = front;
- int curr = 0;
- while(cNode.getNext() != null && curr != index){
- cNode = cNode.getNext();
- curr++;
- }
- return cNode.getVal();
- }
- }
- public int size(){
- return size;
- }
- public String toString(){
- String result = "";
- ListNode<T> curr = front;
- while(curr.getNext() != null){
- result += curr.toString() + "\n";
- curr = curr.getNext();
- }
- return result;
- }
- private class Helper implements Iterator<T>{
- private int index = 0;
- public boolean hasNext(){
- return (index < size);
- }
- public void remove(){
- throw new UnsupportedOperationException();
- }
- public T next(){
- if(hasNext()){
- index++;
- return get(index);
- }
- else{
- throw new NoSuchElementException();
- }
- }
- }
- public Iterator<T> iterator(){
- return new Helper();
- }
- }
Add Comment
Please, Sign In to add comment