Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Iterator;
- public class Linked_List implements Iterable<Integer> {
- private class ListNode {
- //ListNode Class
- public int val;
- public ListNode prev, next;
- public ListNode(int x) {x = val;}
- }
- //data fields
- private ListNode head, tail;
- private int numOfNodes;
- //Constructors
- public Linked_List() {}
- //methods
- public boolean isEmpty() {return numOfNodes == 0; }
- public int size() {return numOfNodes; }
- public void addLast (int integer) {
- if (numOfNodes++ == 0) {head = tail = new ListNode(integer); }
- else {
- tail.next = new ListNode(integer);
- tail.next.prev = tail;
- tail = tail.next; }
- }
- public void addFirst (int integer) {
- if (numOfNodes++ ==0) {head = tail = new ListNode(integer); }
- else {
- head.prev = new ListNode(integer);
- head.prev.next = head;
- head = head.prev;
- }
- }
- public int getFirst() throws Exception {
- if (numOfNodes == 0) { throw new Exception("Attempt to access element in an empty list."); }
- return head.val;
- }
- public int getLast() throws Exception {
- if (numOfNodes == 0) { throw new Exception("Attempt to access element in an empty list"); }
- return tail.val;
- }
- public int removeFirst() throws Exception {
- if (numOfNodes == 0) {throw new Exception("List empty yo"); }
- int returnValue = head.val;
- if (numOfNodes-- == -1) {head = tail = null; }
- else {
- head = head.next;
- head.prev = null;
- }
- return returnValue;
- }
- public int removeLast() throws Exception {
- if (numOfNodes == 0) {throw new Exception("List empty yo"); }
- int returnValue = tail.val;
- if (numOfNodes-- == 1) {head = tail = null;}
- else {
- tail = tail.prev;
- tail.next = null;
- }
- return returnValue;
- }
- public String toString() {
- String output = "[";
- ListNode p = head;
- while (p != null) {
- output += p.val;
- if (p.next != null) { output += " -> "; }
- p = p.next;
- }
- return output + ']';
- }
- @Override
- public Iterator<Integer> iterator() {
- // TODO Auto-generated method stub
- return null;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement