SlideShare a Scribd company logo
1 of 16
Download to read offline
Here is the editable code:
Solution
import java.util.NoSuchElementException;
public class DoublyLinkedListImpl {
private Node head;
private Node tail;
private int size;
public DoublyLinkedListImpl() {
size = 0;
}
private class Node {
E element;
Node next;
Node prev;
public Node(E element, Node next, Node prev) {
this.element = element;
this.next = next;
this.prev = prev;
}
}
public int size() { return size; }
public boolean isEmpty() { return size == 0; }
public void addFirst(E element) {
Node tmp = new Node(element, head, null);
if(head != null ) {head.prev = tmp;}
head = tmp;
if(tail == null) { tail = tmp;}
size++;
System.out.println("adding: "+element);
}
/**
* adds element at the end of the linked list
* @param element
*/
public void addLast(E element) {
Node tmp = new Node(element, null, tail);
if(tail != null) {tail.next = tmp;}
tail = tmp;
if(head == null) { head = tmp;}
size++;
System.out.println("adding: "+element);
}
public void iterateForward(){
System.out.println("iterating forward..");
Node tmp = head;
while(tmp != null){
System.out.println(tmp.element);
tmp = tmp.next;
}
}
/**
* this method walks backward through the linked list
*/
public void iterateBackward(){
System.out.println("iterating backword..");
Node tmp = tail;
while(tmp != null){
System.out.println(tmp.element);
tmp = tmp.prev;
}
}
public E removeFirst() {
if (size == 0) throw new NoSuchElementException();
Node tmp = head;
head = head.next;
head.prev = null;
size--;
System.out.println("deleted: "+tmp.element);
return tmp.element;
}
public E removeLast() {
if (size == 0) throw new NoSuchElementException();
Node tmp = tail;
tail = tail.prev;
tail.next = null;
size--;
System.out.println("deleted: "+tmp.element);
return tmp.element;
}
public static void main(String a[]){
DoublyLinkedListImpl dll = new DoublyLinkedListImpl();
dll.addFirst(10);
dll.addFirst(34);
dll.addLast(56);
dll.addLast(364);
dll.iterateForward();
dll.removeFirst();
dll.removeLast();
dll.iterateBackward();
}
}
import java.util.Scanner;
/* Class Node */
class Node
{
protected int data;
protected Node next, prev;
/* Constructor */
public Node()
{
next = null;
prev = null;
data = 0;
}
/* Constructor */
public Node(int d, Node n, Node p)
{
data = d;
next = n;
prev = p;
}
/* Function to set link to next node */
public void setLinkNext(Node n)
{
next = n;
}
/* Function to set link to previous node */
public void setLinkPrev(Node p)
{
prev = p;
}
/* Funtion to get link to next node */
public Node getLinkNext()
{
return next;
}
/* Function to get link to previous node */
public Node getLinkPrev()
{
return prev;
}
/* Function to set data to node */
public void setData(int d)
{
data = d;
}
/* Function to get data from node */
public int getData()
{
return data;
}
}
/* Class linkedList */
class linkedList
{
protected Node start;
protected Node end ;
public int size;
/* Constructor */
public linkedList()
{
start = null;
end = null;
size = 0;
}
/* Function to check if list is empty */
public boolean isEmpty()
{
return start == null;
}
/* Function to get size of list */
public int getSize()
{
return size;
}
/* Function to insert element at begining */
public void insertAtStart(int val)
{
Node nptr = new Node(val, null, null);
if(start == null)
{
start = nptr;
end = start;
}
else
{
start.setLinkPrev(nptr);
nptr.setLinkNext(start);
start = nptr;
}
size++;
}
/* Function to insert element at end */
public void insertAtEnd(int val)
{
Node nptr = new Node(val, null, null);
if(start == null)
{
start = nptr;
end = start;
}
else
{
nptr.setLinkPrev(end);
end.setLinkNext(nptr);
end = nptr;
}
size++;
}
/* Function to insert element at position */
public void insertAtPos(int val , int pos)
{
Node nptr = new Node(val, null, null);
if (pos == 1)
{
insertAtStart(val);
return;
}
Node ptr = start;
for (int i = 2; i <= size; i++)
{
if (i == pos)
{
Node tmp = ptr.getLinkNext();
ptr.setLinkNext(nptr);
nptr.setLinkPrev(ptr);
nptr.setLinkNext(tmp);
tmp.setLinkPrev(nptr);
}
ptr = ptr.getLinkNext();
}
size++ ;
}
/* Function to delete node at position */
public void deleteAtPos(int pos)
{
if (pos == 1)
{
if (size == 1)
{
start = null;
end = null;
size = 0;
return;
}
start = start.getLinkNext();
start.setLinkPrev(null);
size--;
return ;
}
if (pos == size)
{
end = end.getLinkPrev();
end.setLinkNext(null);
size-- ;
}
Node ptr = start.getLinkNext();
for (int i = 2; i <= size; i++)
{
if (i == pos)
{
Node p = ptr.getLinkPrev();
Node n = ptr.getLinkNext();
p.setLinkNext(n);
n.setLinkPrev(p);
size-- ;
return;
}
ptr = ptr.getLinkNext();
}
}
/* Function to display status of list */
public void display()
{
System.out.print(" Doubly Linked List = ");
if (size == 0)
{
System.out.print("empty ");
return;
}
if (start.getLinkNext() == null)
{
System.out.println(start.getData() );
return;
}
Node ptr = start;
System.out.print(start.getData()+ " <-> ");
ptr = start.getLinkNext();
while (ptr.getLinkNext() != null)
{
System.out.print(ptr.getData()+ " <-> ");
ptr = ptr.getLinkNext();
}
System.out.print(ptr.getData()+ " ");
}
}
/* Class DoublyLinkedList */
public class DoublyLinkedList
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
/* Creating object of linkedList */
linkedList list = new linkedList();
System.out.println("Doubly Linked List Test ");
char ch;
/* Perform list operations */
do
{
System.out.println(" Doubly Linked List Operations ");
System.out.println("1. insert at begining");
System.out.println("2. insert at end");
System.out.println("3. insert at position");
System.out.println("4. delete at position");
System.out.println("5. check empty");
System.out.println("6. get size");
int choice = scan.nextInt();
switch (choice)
{
case 1 :
System.out.println("Enter integer element to insert");
list.insertAtStart( scan.nextInt() );
break;
case 2 :
System.out.println("Enter integer element to insert");
list.insertAtEnd( scan.nextInt() );
break;
case 3 :
System.out.println("Enter integer element to insert");
int num = scan.nextInt() ;
System.out.println("Enter position");
int pos = scan.nextInt() ;
if (pos < 1 || pos > list.getSize() )
System.out.println("Invalid position ");
else
list.insertAtPos(num, pos);
break;
case 4 :
System.out.println("Enter position");
int p = scan.nextInt() ;
if (p < 1 || p > list.getSize() )
System.out.println("Invalid position ");
else
list.deleteAtPos(p);
break;
case 5 :
System.out.println("Empty status = "+ list.isEmpty());
break;
case 6 :
System.out.println("Size = "+ list.getSize() +"  ");
break;
default :
System.out.println("Wrong Entry  ");
break;
}
/* Display List */
list.display();
System.out.println(" Do you want to continue (Type y or n)  ");
ch = scan.next().charAt(0);
} while (ch == 'Y'|| ch == 'y');
}
}
import java.util.ListIterator;
import java.util.NoSuchElementException;
public class DoublyLinkedList implements Iterable {
private int n; // number of elements on list
private Node pre; // sentinel before first item
private Node post; // sentinel after last item
public DoublyLinkedList() {
pre = new Node();
post = new Node();
pre.next = post;
post.prev = pre;
}
// linked list node helper data type
private class Node {
private Item item;
private Node next;
private Node prev;
}
public boolean isEmpty() { return n == 0; }
public int size() { return n; }
// add the item to the list
public void add(Item item) {
Node last = post.prev;
Node x = new Node();
x.item = item;
x.next = post;
x.prev = last;
post.prev = x;
last.next = x;
n++;
}
public ListIterator iterator() { return new DoublyLinkedListIterator(); }
// assumes no calls to DoublyLinkedList.add() during iteration
private class DoublyLinkedListIterator implements ListIterator {
private Node current = pre.next; // the node that is returned by next()
private Node lastAccessed = null; // the last node to be returned by prev() or next()
// reset to null upon intervening remove() or add()
private int index = 0;
public boolean hasNext() { return index < n; }
public boolean hasPrevious() { return index > 0; }
public int previousIndex() { return index - 1; }
public int nextIndex() { return index; }
public Item next() {
if (!hasNext()) throw new NoSuchElementException();
lastAccessed = current;
Item item = current.item;
current = current.next;
index++;
return item;
}
public Item previous() {
if (!hasPrevious()) throw new NoSuchElementException();
current = current.prev;
index--;
lastAccessed = current;
return current.item;
}
// replace the item of the element that was last accessed by next() or previous()
// condition: no calls to remove() or add() after last call to next() or previous()
public void set(Item item) {
if (lastAccessed == null) throw new IllegalStateException();
lastAccessed.item = item;
}
// remove the element that was last accessed by next() or previous()
// condition: no calls to remove() or add() after last call to next() or previous()
public void remove() {
if (lastAccessed == null) throw new IllegalStateException();
Node x = lastAccessed.prev;
Node y = lastAccessed.next;
x.next = y;
y.prev = x;
n--;
if (current == lastAccessed)
current = y;
else
index--;
lastAccessed = null;
}
// add element to list
public void add(Item item) {
Node x = current.prev;
Node y = new Node();
Node z = current;
y.item = item;
x.next = y;
y.next = z;
z.prev = y;
y.prev = x;
n++;
index++;
lastAccessed = null;
}
}
public String toString() {
StringBuilder s = new StringBuilder();
for (Item item : this)
s.append(item + " ");
return s.toString();
}
// a test client
public static void main(String[] args) {
int n = Integer.parseInt(args[0]);
// add elements 1, ..., n
StdOut.println(n + " random integers between 0 and 99");
DoublyLinkedList list = new DoublyLinkedList();
for (int i = 0; i < n; i++)
list.add(StdRandom.uniform(100));
StdOut.println(list);
StdOut.println();
ListIterator iterator = list.iterator();
// go forwards with next() and set()
StdOut.println("add 1 to each element via next() and set()");
while (iterator.hasNext()) {
int x = iterator.next();
iterator.set(x + 1);
}
StdOut.println(list);
StdOut.println();
// go backwards with previous() and set()
StdOut.println("multiply each element by 3 via previous() and set()");
while (iterator.hasPrevious()) {
int x = iterator.previous();
iterator.set(x + x + x);
}
StdOut.println(list);
StdOut.println();
// remove all elements that are multiples of 4 via next() and remove()
StdOut.println("remove elements that are a multiple of 4 via next() and remove()");
while (iterator.hasNext()) {
int x = iterator.next();
if (x % 4 == 0) iterator.remove();
}
StdOut.println(list);
StdOut.println();
// remove all even elements via previous() and remove()
StdOut.println("remove elements that are even via previous() and remove()");
while (iterator.hasPrevious()) {
int x = iterator.previous();
if (x % 2 == 0) iterator.remove();
}
StdOut.println(list);
StdOut.println();
// add elements via next() and add()
StdOut.println("add elements via next() and add()");
while (iterator.hasNext()) {
int x = iterator.next();
iterator.add(x + 1);
}
StdOut.println(list);
StdOut.println();
// add elements via previous() and add()
StdOut.println("add elements via previous() and add()");
while (iterator.hasPrevious()) {
int x = iterator.previous();
iterator.add(x * 10);
iterator.previous();
}
StdOut.println(list);
StdOut.println();
}
}

More Related Content

Similar to Here is the editable codeSolutionimport java.util.NoSuchEleme.pdf

Hi, Please find my code.I have correted all of your classes.Plea.pdf
Hi, Please find my code.I have correted all of your classes.Plea.pdfHi, Please find my code.I have correted all of your classes.Plea.pdf
Hi, Please find my code.I have correted all of your classes.Plea.pdfpritikulkarni20
 
How do I fix it in LinkedList.javaLinkedList.java Define.pdf
How do I fix it in LinkedList.javaLinkedList.java Define.pdfHow do I fix it in LinkedList.javaLinkedList.java Define.pdf
How do I fix it in LinkedList.javaLinkedList.java Define.pdfmail931892
 
How do I fix it in javaLinkedList.java Defines a doubl.pdf
How do I fix it in javaLinkedList.java Defines a doubl.pdfHow do I fix it in javaLinkedList.java Defines a doubl.pdf
How do I fix it in javaLinkedList.java Defines a doubl.pdffmac5
 
using set identitiesSolutionimport java.util.Scanner; c.pdf
using set identitiesSolutionimport java.util.Scanner;  c.pdfusing set identitiesSolutionimport java.util.Scanner;  c.pdf
using set identitiesSolutionimport java.util.Scanner; c.pdfexcellentmobilesabc
 
Implement a queue using a linkedlist (java)SolutionLinkedQueue.pdf
Implement a queue using a linkedlist (java)SolutionLinkedQueue.pdfImplement a queue using a linkedlist (java)SolutionLinkedQueue.pdf
Implement a queue using a linkedlist (java)SolutionLinkedQueue.pdfkostikjaylonshaewe47
 
import java.util.Iterator; import java.util.NoSuchElementException; .pdf
  import java.util.Iterator; import java.util.NoSuchElementException; .pdf  import java.util.Iterator; import java.util.NoSuchElementException; .pdf
import java.util.Iterator; import java.util.NoSuchElementException; .pdfdeepakangel
 
How do I fix it in LinkedList.javaLabProgram.javaLinkedList.jav.pdf
How do I fix it in LinkedList.javaLabProgram.javaLinkedList.jav.pdfHow do I fix it in LinkedList.javaLabProgram.javaLinkedList.jav.pdf
How do I fix it in LinkedList.javaLabProgram.javaLinkedList.jav.pdfmail931892
 
Exception to indicate that Singly LinkedList is empty. .pdf
  Exception to indicate that Singly LinkedList is empty. .pdf  Exception to indicate that Singly LinkedList is empty. .pdf
Exception to indicate that Singly LinkedList is empty. .pdfaravlitraders2012
 
import java-util-Iterator- import java-util-NoSuchElementException- im.pdf
import java-util-Iterator- import java-util-NoSuchElementException- im.pdfimport java-util-Iterator- import java-util-NoSuchElementException- im.pdf
import java-util-Iterator- import java-util-NoSuchElementException- im.pdfStewart29UReesa
 
package com.java2novice.ds.linkedlist;import java.util.NoSuchEleme.pdf
package com.java2novice.ds.linkedlist;import java.util.NoSuchEleme.pdfpackage com.java2novice.ds.linkedlist;import java.util.NoSuchEleme.pdf
package com.java2novice.ds.linkedlist;import java.util.NoSuchEleme.pdfaptind
 
PROBLEM STATEMENTIn this assignment, you will complete DoubleEnde.pdf
PROBLEM STATEMENTIn this assignment, you will complete DoubleEnde.pdfPROBLEM STATEMENTIn this assignment, you will complete DoubleEnde.pdf
PROBLEM STATEMENTIn this assignment, you will complete DoubleEnde.pdfclimatecontrolsv
 
#ifndef LINKED_LIST_ #define LINKED_LIST_ templateclass It.pdf
 #ifndef LINKED_LIST_ #define LINKED_LIST_ templateclass It.pdf #ifndef LINKED_LIST_ #define LINKED_LIST_ templateclass It.pdf
#ifndef LINKED_LIST_ #define LINKED_LIST_ templateclass It.pdfangelsfashion1
 
How do I fix it in LinkedList.javathis is what i didLabProgra.pdf
How do I fix it in LinkedList.javathis is what i didLabProgra.pdfHow do I fix it in LinkedList.javathis is what i didLabProgra.pdf
How do I fix it in LinkedList.javathis is what i didLabProgra.pdfmail931892
 
For the code below complete the preOrder() method so that it perform.pdf
For the code below complete the preOrder() method so that it perform.pdfFor the code below complete the preOrder() method so that it perform.pdf
For the code below complete the preOrder() method so that it perform.pdfxlynettalampleyxc
 
Implement the additional 5 methods as indicated in the LinkedList fi.pdf
Implement the additional 5 methods as indicated in the LinkedList fi.pdfImplement the additional 5 methods as indicated in the LinkedList fi.pdf
Implement the additional 5 methods as indicated in the LinkedList fi.pdffootstatus
 
#includeiostream#includecstdio#includecstdlibusing names.pdf
#includeiostream#includecstdio#includecstdlibusing names.pdf#includeiostream#includecstdio#includecstdlibusing names.pdf
#includeiostream#includecstdio#includecstdlibusing names.pdfKUNALHARCHANDANI1
 
JAVA Demonstrate the use of your APL in a PartB_Driver class by doing.docx
JAVA Demonstrate the use of your APL in a PartB_Driver class by doing.docxJAVA Demonstrate the use of your APL in a PartB_Driver class by doing.docx
JAVA Demonstrate the use of your APL in a PartB_Driver class by doing.docxGavinUJtMathist
 
Help please, I have attached LinkedList.cpp and LinkedList.hPlease.pdf
Help please, I have attached LinkedList.cpp and LinkedList.hPlease.pdfHelp please, I have attached LinkedList.cpp and LinkedList.hPlease.pdf
Help please, I have attached LinkedList.cpp and LinkedList.hPlease.pdfarorastores
 
This is problem is same problem which i submitted on 22017, I just.pdf
This is problem is same problem which i submitted on 22017, I just.pdfThis is problem is same problem which i submitted on 22017, I just.pdf
This is problem is same problem which i submitted on 22017, I just.pdffcaindore
 
Implement the unsorted single linked list as we did in the class and .pdf
Implement the unsorted single linked list as we did in the class and .pdfImplement the unsorted single linked list as we did in the class and .pdf
Implement the unsorted single linked list as we did in the class and .pdfarihantstoneart
 

Similar to Here is the editable codeSolutionimport java.util.NoSuchEleme.pdf (20)

Hi, Please find my code.I have correted all of your classes.Plea.pdf
Hi, Please find my code.I have correted all of your classes.Plea.pdfHi, Please find my code.I have correted all of your classes.Plea.pdf
Hi, Please find my code.I have correted all of your classes.Plea.pdf
 
How do I fix it in LinkedList.javaLinkedList.java Define.pdf
How do I fix it in LinkedList.javaLinkedList.java Define.pdfHow do I fix it in LinkedList.javaLinkedList.java Define.pdf
How do I fix it in LinkedList.javaLinkedList.java Define.pdf
 
How do I fix it in javaLinkedList.java Defines a doubl.pdf
How do I fix it in javaLinkedList.java Defines a doubl.pdfHow do I fix it in javaLinkedList.java Defines a doubl.pdf
How do I fix it in javaLinkedList.java Defines a doubl.pdf
 
using set identitiesSolutionimport java.util.Scanner; c.pdf
using set identitiesSolutionimport java.util.Scanner;  c.pdfusing set identitiesSolutionimport java.util.Scanner;  c.pdf
using set identitiesSolutionimport java.util.Scanner; c.pdf
 
Implement a queue using a linkedlist (java)SolutionLinkedQueue.pdf
Implement a queue using a linkedlist (java)SolutionLinkedQueue.pdfImplement a queue using a linkedlist (java)SolutionLinkedQueue.pdf
Implement a queue using a linkedlist (java)SolutionLinkedQueue.pdf
 
import java.util.Iterator; import java.util.NoSuchElementException; .pdf
  import java.util.Iterator; import java.util.NoSuchElementException; .pdf  import java.util.Iterator; import java.util.NoSuchElementException; .pdf
import java.util.Iterator; import java.util.NoSuchElementException; .pdf
 
How do I fix it in LinkedList.javaLabProgram.javaLinkedList.jav.pdf
How do I fix it in LinkedList.javaLabProgram.javaLinkedList.jav.pdfHow do I fix it in LinkedList.javaLabProgram.javaLinkedList.jav.pdf
How do I fix it in LinkedList.javaLabProgram.javaLinkedList.jav.pdf
 
Exception to indicate that Singly LinkedList is empty. .pdf
  Exception to indicate that Singly LinkedList is empty. .pdf  Exception to indicate that Singly LinkedList is empty. .pdf
Exception to indicate that Singly LinkedList is empty. .pdf
 
import java-util-Iterator- import java-util-NoSuchElementException- im.pdf
import java-util-Iterator- import java-util-NoSuchElementException- im.pdfimport java-util-Iterator- import java-util-NoSuchElementException- im.pdf
import java-util-Iterator- import java-util-NoSuchElementException- im.pdf
 
package com.java2novice.ds.linkedlist;import java.util.NoSuchEleme.pdf
package com.java2novice.ds.linkedlist;import java.util.NoSuchEleme.pdfpackage com.java2novice.ds.linkedlist;import java.util.NoSuchEleme.pdf
package com.java2novice.ds.linkedlist;import java.util.NoSuchEleme.pdf
 
PROBLEM STATEMENTIn this assignment, you will complete DoubleEnde.pdf
PROBLEM STATEMENTIn this assignment, you will complete DoubleEnde.pdfPROBLEM STATEMENTIn this assignment, you will complete DoubleEnde.pdf
PROBLEM STATEMENTIn this assignment, you will complete DoubleEnde.pdf
 
#ifndef LINKED_LIST_ #define LINKED_LIST_ templateclass It.pdf
 #ifndef LINKED_LIST_ #define LINKED_LIST_ templateclass It.pdf #ifndef LINKED_LIST_ #define LINKED_LIST_ templateclass It.pdf
#ifndef LINKED_LIST_ #define LINKED_LIST_ templateclass It.pdf
 
How do I fix it in LinkedList.javathis is what i didLabProgra.pdf
How do I fix it in LinkedList.javathis is what i didLabProgra.pdfHow do I fix it in LinkedList.javathis is what i didLabProgra.pdf
How do I fix it in LinkedList.javathis is what i didLabProgra.pdf
 
For the code below complete the preOrder() method so that it perform.pdf
For the code below complete the preOrder() method so that it perform.pdfFor the code below complete the preOrder() method so that it perform.pdf
For the code below complete the preOrder() method so that it perform.pdf
 
Implement the additional 5 methods as indicated in the LinkedList fi.pdf
Implement the additional 5 methods as indicated in the LinkedList fi.pdfImplement the additional 5 methods as indicated in the LinkedList fi.pdf
Implement the additional 5 methods as indicated in the LinkedList fi.pdf
 
#includeiostream#includecstdio#includecstdlibusing names.pdf
#includeiostream#includecstdio#includecstdlibusing names.pdf#includeiostream#includecstdio#includecstdlibusing names.pdf
#includeiostream#includecstdio#includecstdlibusing names.pdf
 
JAVA Demonstrate the use of your APL in a PartB_Driver class by doing.docx
JAVA Demonstrate the use of your APL in a PartB_Driver class by doing.docxJAVA Demonstrate the use of your APL in a PartB_Driver class by doing.docx
JAVA Demonstrate the use of your APL in a PartB_Driver class by doing.docx
 
Help please, I have attached LinkedList.cpp and LinkedList.hPlease.pdf
Help please, I have attached LinkedList.cpp and LinkedList.hPlease.pdfHelp please, I have attached LinkedList.cpp and LinkedList.hPlease.pdf
Help please, I have attached LinkedList.cpp and LinkedList.hPlease.pdf
 
This is problem is same problem which i submitted on 22017, I just.pdf
This is problem is same problem which i submitted on 22017, I just.pdfThis is problem is same problem which i submitted on 22017, I just.pdf
This is problem is same problem which i submitted on 22017, I just.pdf
 
Implement the unsorted single linked list as we did in the class and .pdf
Implement the unsorted single linked list as we did in the class and .pdfImplement the unsorted single linked list as we did in the class and .pdf
Implement the unsorted single linked list as we did in the class and .pdf
 

More from arrowmobile

ESSAY QUESTIONS - ETHICSLewis Archer is an outside auditor who dis.pdf
ESSAY QUESTIONS - ETHICSLewis Archer is an outside auditor who dis.pdfESSAY QUESTIONS - ETHICSLewis Archer is an outside auditor who dis.pdf
ESSAY QUESTIONS - ETHICSLewis Archer is an outside auditor who dis.pdfarrowmobile
 
Determine whether each of following statements is true or false. Prov.pdf
Determine whether each of following statements is true or false. Prov.pdfDetermine whether each of following statements is true or false. Prov.pdf
Determine whether each of following statements is true or false. Prov.pdfarrowmobile
 
describe the oceans solubility pump and the oceans biological pump u.pdf
describe the oceans solubility pump and the oceans biological pump u.pdfdescribe the oceans solubility pump and the oceans biological pump u.pdf
describe the oceans solubility pump and the oceans biological pump u.pdfarrowmobile
 
Describe how bacterial cells compare to onion cells.SolutionPl.pdf
Describe how bacterial cells compare to onion cells.SolutionPl.pdfDescribe how bacterial cells compare to onion cells.SolutionPl.pdf
Describe how bacterial cells compare to onion cells.SolutionPl.pdfarrowmobile
 
A facility is to be designed with 7 departments (Dl-D7) such that the.pdf
A facility is to be designed with 7 departments (Dl-D7) such that the.pdfA facility is to be designed with 7 departments (Dl-D7) such that the.pdf
A facility is to be designed with 7 departments (Dl-D7) such that the.pdfarrowmobile
 
Briefly discuss each of the chronological steps in the process o.pdf
Briefly discuss each of the chronological steps in the process o.pdfBriefly discuss each of the chronological steps in the process o.pdf
Briefly discuss each of the chronological steps in the process o.pdfarrowmobile
 
Which protocol uses tunneling to send PPP packets over a nonsecure n.pdf
Which protocol uses tunneling to send PPP packets over a nonsecure n.pdfWhich protocol uses tunneling to send PPP packets over a nonsecure n.pdf
Which protocol uses tunneling to send PPP packets over a nonsecure n.pdfarrowmobile
 
What is the simple formula for figuring Addition to Retained earn.pdf
What is the simple formula for figuring Addition to Retained earn.pdfWhat is the simple formula for figuring Addition to Retained earn.pdf
What is the simple formula for figuring Addition to Retained earn.pdfarrowmobile
 
Why can we not see individual photons, but rather light appear to us.pdf
Why can we not see individual photons, but rather light appear to us.pdfWhy can we not see individual photons, but rather light appear to us.pdf
Why can we not see individual photons, but rather light appear to us.pdfarrowmobile
 
Why is it important to study reactions norms to understand phenotypi.pdf
Why is it important to study reactions norms to understand phenotypi.pdfWhy is it important to study reactions norms to understand phenotypi.pdf
Why is it important to study reactions norms to understand phenotypi.pdfarrowmobile
 
Which of the following is true about the nucleolusA)found in prok.pdf
Which of the following is true about the nucleolusA)found in prok.pdfWhich of the following is true about the nucleolusA)found in prok.pdf
Which of the following is true about the nucleolusA)found in prok.pdfarrowmobile
 
1. The gene OCA2 on chromosome 15 confers eye color in humans. The m.pdf
1. The gene OCA2 on chromosome 15 confers eye color in humans. The m.pdf1. The gene OCA2 on chromosome 15 confers eye color in humans. The m.pdf
1. The gene OCA2 on chromosome 15 confers eye color in humans. The m.pdfarrowmobile
 
The graph of a periodic function is given below.- Define a functio.pdf
The graph of a periodic function is given below.- Define a functio.pdfThe graph of a periodic function is given below.- Define a functio.pdf
The graph of a periodic function is given below.- Define a functio.pdfarrowmobile
 
What is the three point notationSolutionIn a 3D Cartesian coo.pdf
What is the three point notationSolutionIn a 3D Cartesian coo.pdfWhat is the three point notationSolutionIn a 3D Cartesian coo.pdf
What is the three point notationSolutionIn a 3D Cartesian coo.pdfarrowmobile
 
What is SOPA Discuss SOPA development and enforcement.Solution.pdf
What is SOPA Discuss SOPA development and enforcement.Solution.pdfWhat is SOPA Discuss SOPA development and enforcement.Solution.pdf
What is SOPA Discuss SOPA development and enforcement.Solution.pdfarrowmobile
 
Walking through the forest you come to a dry creek bed, and notice t.pdf
Walking through the forest you come to a dry creek bed, and notice t.pdfWalking through the forest you come to a dry creek bed, and notice t.pdf
Walking through the forest you come to a dry creek bed, and notice t.pdfarrowmobile
 
What does decrease in water potential mean (Lower negative value.pdf
What does decrease in water potential mean (Lower negative value.pdfWhat does decrease in water potential mean (Lower negative value.pdf
What does decrease in water potential mean (Lower negative value.pdfarrowmobile
 
Understand and describe the following technologies Flow Cytometry, .pdf
Understand and describe the following technologies Flow Cytometry, .pdfUnderstand and describe the following technologies Flow Cytometry, .pdf
Understand and describe the following technologies Flow Cytometry, .pdfarrowmobile
 
1. What would determine protein levels in cells2.Draw a hypotheti.pdf
1. What would determine protein levels in cells2.Draw a hypotheti.pdf1. What would determine protein levels in cells2.Draw a hypotheti.pdf
1. What would determine protein levels in cells2.Draw a hypotheti.pdfarrowmobile
 
Tversky and Kahneman1 asked a group of subjects to carry out the fol.pdf
Tversky and Kahneman1 asked a group of subjects to carry out the fol.pdfTversky and Kahneman1 asked a group of subjects to carry out the fol.pdf
Tversky and Kahneman1 asked a group of subjects to carry out the fol.pdfarrowmobile
 

More from arrowmobile (20)

ESSAY QUESTIONS - ETHICSLewis Archer is an outside auditor who dis.pdf
ESSAY QUESTIONS - ETHICSLewis Archer is an outside auditor who dis.pdfESSAY QUESTIONS - ETHICSLewis Archer is an outside auditor who dis.pdf
ESSAY QUESTIONS - ETHICSLewis Archer is an outside auditor who dis.pdf
 
Determine whether each of following statements is true or false. Prov.pdf
Determine whether each of following statements is true or false. Prov.pdfDetermine whether each of following statements is true or false. Prov.pdf
Determine whether each of following statements is true or false. Prov.pdf
 
describe the oceans solubility pump and the oceans biological pump u.pdf
describe the oceans solubility pump and the oceans biological pump u.pdfdescribe the oceans solubility pump and the oceans biological pump u.pdf
describe the oceans solubility pump and the oceans biological pump u.pdf
 
Describe how bacterial cells compare to onion cells.SolutionPl.pdf
Describe how bacterial cells compare to onion cells.SolutionPl.pdfDescribe how bacterial cells compare to onion cells.SolutionPl.pdf
Describe how bacterial cells compare to onion cells.SolutionPl.pdf
 
A facility is to be designed with 7 departments (Dl-D7) such that the.pdf
A facility is to be designed with 7 departments (Dl-D7) such that the.pdfA facility is to be designed with 7 departments (Dl-D7) such that the.pdf
A facility is to be designed with 7 departments (Dl-D7) such that the.pdf
 
Briefly discuss each of the chronological steps in the process o.pdf
Briefly discuss each of the chronological steps in the process o.pdfBriefly discuss each of the chronological steps in the process o.pdf
Briefly discuss each of the chronological steps in the process o.pdf
 
Which protocol uses tunneling to send PPP packets over a nonsecure n.pdf
Which protocol uses tunneling to send PPP packets over a nonsecure n.pdfWhich protocol uses tunneling to send PPP packets over a nonsecure n.pdf
Which protocol uses tunneling to send PPP packets over a nonsecure n.pdf
 
What is the simple formula for figuring Addition to Retained earn.pdf
What is the simple formula for figuring Addition to Retained earn.pdfWhat is the simple formula for figuring Addition to Retained earn.pdf
What is the simple formula for figuring Addition to Retained earn.pdf
 
Why can we not see individual photons, but rather light appear to us.pdf
Why can we not see individual photons, but rather light appear to us.pdfWhy can we not see individual photons, but rather light appear to us.pdf
Why can we not see individual photons, but rather light appear to us.pdf
 
Why is it important to study reactions norms to understand phenotypi.pdf
Why is it important to study reactions norms to understand phenotypi.pdfWhy is it important to study reactions norms to understand phenotypi.pdf
Why is it important to study reactions norms to understand phenotypi.pdf
 
Which of the following is true about the nucleolusA)found in prok.pdf
Which of the following is true about the nucleolusA)found in prok.pdfWhich of the following is true about the nucleolusA)found in prok.pdf
Which of the following is true about the nucleolusA)found in prok.pdf
 
1. The gene OCA2 on chromosome 15 confers eye color in humans. The m.pdf
1. The gene OCA2 on chromosome 15 confers eye color in humans. The m.pdf1. The gene OCA2 on chromosome 15 confers eye color in humans. The m.pdf
1. The gene OCA2 on chromosome 15 confers eye color in humans. The m.pdf
 
The graph of a periodic function is given below.- Define a functio.pdf
The graph of a periodic function is given below.- Define a functio.pdfThe graph of a periodic function is given below.- Define a functio.pdf
The graph of a periodic function is given below.- Define a functio.pdf
 
What is the three point notationSolutionIn a 3D Cartesian coo.pdf
What is the three point notationSolutionIn a 3D Cartesian coo.pdfWhat is the three point notationSolutionIn a 3D Cartesian coo.pdf
What is the three point notationSolutionIn a 3D Cartesian coo.pdf
 
What is SOPA Discuss SOPA development and enforcement.Solution.pdf
What is SOPA Discuss SOPA development and enforcement.Solution.pdfWhat is SOPA Discuss SOPA development and enforcement.Solution.pdf
What is SOPA Discuss SOPA development and enforcement.Solution.pdf
 
Walking through the forest you come to a dry creek bed, and notice t.pdf
Walking through the forest you come to a dry creek bed, and notice t.pdfWalking through the forest you come to a dry creek bed, and notice t.pdf
Walking through the forest you come to a dry creek bed, and notice t.pdf
 
What does decrease in water potential mean (Lower negative value.pdf
What does decrease in water potential mean (Lower negative value.pdfWhat does decrease in water potential mean (Lower negative value.pdf
What does decrease in water potential mean (Lower negative value.pdf
 
Understand and describe the following technologies Flow Cytometry, .pdf
Understand and describe the following technologies Flow Cytometry, .pdfUnderstand and describe the following technologies Flow Cytometry, .pdf
Understand and describe the following technologies Flow Cytometry, .pdf
 
1. What would determine protein levels in cells2.Draw a hypotheti.pdf
1. What would determine protein levels in cells2.Draw a hypotheti.pdf1. What would determine protein levels in cells2.Draw a hypotheti.pdf
1. What would determine protein levels in cells2.Draw a hypotheti.pdf
 
Tversky and Kahneman1 asked a group of subjects to carry out the fol.pdf
Tversky and Kahneman1 asked a group of subjects to carry out the fol.pdfTversky and Kahneman1 asked a group of subjects to carry out the fol.pdf
Tversky and Kahneman1 asked a group of subjects to carry out the fol.pdf
 

Recently uploaded

Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxAvyJaneVismanos
 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfadityarao40181
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsKarinaGenton
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptxENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptxAnaBeatriceAblay2
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxRaymartEstabillo3
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfakmcokerachita
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,Virag Sontakke
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerunnathinaik
 

Recently uploaded (20)

Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptx
 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdf
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its Characteristics
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptxENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdf
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developer
 

Here is the editable codeSolutionimport java.util.NoSuchEleme.pdf

  • 1. Here is the editable code: Solution import java.util.NoSuchElementException; public class DoublyLinkedListImpl { private Node head; private Node tail; private int size; public DoublyLinkedListImpl() { size = 0; } private class Node { E element; Node next; Node prev; public Node(E element, Node next, Node prev) { this.element = element; this.next = next; this.prev = prev; } } public int size() { return size; } public boolean isEmpty() { return size == 0; } public void addFirst(E element) {
  • 2. Node tmp = new Node(element, head, null); if(head != null ) {head.prev = tmp;} head = tmp; if(tail == null) { tail = tmp;} size++; System.out.println("adding: "+element); } /** * adds element at the end of the linked list * @param element */ public void addLast(E element) { Node tmp = new Node(element, null, tail); if(tail != null) {tail.next = tmp;} tail = tmp; if(head == null) { head = tmp;} size++; System.out.println("adding: "+element); } public void iterateForward(){ System.out.println("iterating forward.."); Node tmp = head; while(tmp != null){ System.out.println(tmp.element); tmp = tmp.next; } } /** * this method walks backward through the linked list */
  • 3. public void iterateBackward(){ System.out.println("iterating backword.."); Node tmp = tail; while(tmp != null){ System.out.println(tmp.element); tmp = tmp.prev; } } public E removeFirst() { if (size == 0) throw new NoSuchElementException(); Node tmp = head; head = head.next; head.prev = null; size--; System.out.println("deleted: "+tmp.element); return tmp.element; } public E removeLast() { if (size == 0) throw new NoSuchElementException(); Node tmp = tail; tail = tail.prev; tail.next = null; size--; System.out.println("deleted: "+tmp.element); return tmp.element; } public static void main(String a[]){ DoublyLinkedListImpl dll = new DoublyLinkedListImpl(); dll.addFirst(10);
  • 4. dll.addFirst(34); dll.addLast(56); dll.addLast(364); dll.iterateForward(); dll.removeFirst(); dll.removeLast(); dll.iterateBackward(); } } import java.util.Scanner; /* Class Node */ class Node { protected int data; protected Node next, prev; /* Constructor */ public Node() { next = null; prev = null; data = 0; } /* Constructor */ public Node(int d, Node n, Node p) { data = d; next = n; prev = p; } /* Function to set link to next node */ public void setLinkNext(Node n) { next = n;
  • 5. } /* Function to set link to previous node */ public void setLinkPrev(Node p) { prev = p; } /* Funtion to get link to next node */ public Node getLinkNext() { return next; } /* Function to get link to previous node */ public Node getLinkPrev() { return prev; } /* Function to set data to node */ public void setData(int d) { data = d; } /* Function to get data from node */ public int getData() { return data; } } /* Class linkedList */ class linkedList { protected Node start; protected Node end ; public int size; /* Constructor */
  • 6. public linkedList() { start = null; end = null; size = 0; } /* Function to check if list is empty */ public boolean isEmpty() { return start == null; } /* Function to get size of list */ public int getSize() { return size; } /* Function to insert element at begining */ public void insertAtStart(int val) { Node nptr = new Node(val, null, null); if(start == null) { start = nptr; end = start; } else { start.setLinkPrev(nptr); nptr.setLinkNext(start); start = nptr; } size++; } /* Function to insert element at end */ public void insertAtEnd(int val) {
  • 7. Node nptr = new Node(val, null, null); if(start == null) { start = nptr; end = start; } else { nptr.setLinkPrev(end); end.setLinkNext(nptr); end = nptr; } size++; } /* Function to insert element at position */ public void insertAtPos(int val , int pos) { Node nptr = new Node(val, null, null); if (pos == 1) { insertAtStart(val); return; } Node ptr = start; for (int i = 2; i <= size; i++) { if (i == pos) { Node tmp = ptr.getLinkNext(); ptr.setLinkNext(nptr); nptr.setLinkPrev(ptr); nptr.setLinkNext(tmp); tmp.setLinkPrev(nptr); } ptr = ptr.getLinkNext(); }
  • 8. size++ ; } /* Function to delete node at position */ public void deleteAtPos(int pos) { if (pos == 1) { if (size == 1) { start = null; end = null; size = 0; return; } start = start.getLinkNext(); start.setLinkPrev(null); size--; return ; } if (pos == size) { end = end.getLinkPrev(); end.setLinkNext(null); size-- ; } Node ptr = start.getLinkNext(); for (int i = 2; i <= size; i++) { if (i == pos) { Node p = ptr.getLinkPrev(); Node n = ptr.getLinkNext(); p.setLinkNext(n); n.setLinkPrev(p); size-- ;
  • 9. return; } ptr = ptr.getLinkNext(); } } /* Function to display status of list */ public void display() { System.out.print(" Doubly Linked List = "); if (size == 0) { System.out.print("empty "); return; } if (start.getLinkNext() == null) { System.out.println(start.getData() ); return; } Node ptr = start; System.out.print(start.getData()+ " <-> "); ptr = start.getLinkNext(); while (ptr.getLinkNext() != null) { System.out.print(ptr.getData()+ " <-> "); ptr = ptr.getLinkNext(); } System.out.print(ptr.getData()+ " "); } } /* Class DoublyLinkedList */ public class DoublyLinkedList { public static void main(String[] args) {
  • 10. Scanner scan = new Scanner(System.in); /* Creating object of linkedList */ linkedList list = new linkedList(); System.out.println("Doubly Linked List Test "); char ch; /* Perform list operations */ do { System.out.println(" Doubly Linked List Operations "); System.out.println("1. insert at begining"); System.out.println("2. insert at end"); System.out.println("3. insert at position"); System.out.println("4. delete at position"); System.out.println("5. check empty"); System.out.println("6. get size"); int choice = scan.nextInt(); switch (choice) { case 1 : System.out.println("Enter integer element to insert"); list.insertAtStart( scan.nextInt() ); break; case 2 : System.out.println("Enter integer element to insert"); list.insertAtEnd( scan.nextInt() ); break; case 3 : System.out.println("Enter integer element to insert"); int num = scan.nextInt() ; System.out.println("Enter position"); int pos = scan.nextInt() ; if (pos < 1 || pos > list.getSize() ) System.out.println("Invalid position "); else list.insertAtPos(num, pos);
  • 11. break; case 4 : System.out.println("Enter position"); int p = scan.nextInt() ; if (p < 1 || p > list.getSize() ) System.out.println("Invalid position "); else list.deleteAtPos(p); break; case 5 : System.out.println("Empty status = "+ list.isEmpty()); break; case 6 : System.out.println("Size = "+ list.getSize() +" "); break; default : System.out.println("Wrong Entry "); break; } /* Display List */ list.display(); System.out.println(" Do you want to continue (Type y or n) "); ch = scan.next().charAt(0); } while (ch == 'Y'|| ch == 'y'); } } import java.util.ListIterator; import java.util.NoSuchElementException; public class DoublyLinkedList implements Iterable { private int n; // number of elements on list private Node pre; // sentinel before first item private Node post; // sentinel after last item public DoublyLinkedList() { pre = new Node();
  • 12. post = new Node(); pre.next = post; post.prev = pre; } // linked list node helper data type private class Node { private Item item; private Node next; private Node prev; } public boolean isEmpty() { return n == 0; } public int size() { return n; } // add the item to the list public void add(Item item) { Node last = post.prev; Node x = new Node(); x.item = item; x.next = post; x.prev = last; post.prev = x; last.next = x; n++; } public ListIterator iterator() { return new DoublyLinkedListIterator(); } // assumes no calls to DoublyLinkedList.add() during iteration private class DoublyLinkedListIterator implements ListIterator { private Node current = pre.next; // the node that is returned by next() private Node lastAccessed = null; // the last node to be returned by prev() or next() // reset to null upon intervening remove() or add() private int index = 0; public boolean hasNext() { return index < n; } public boolean hasPrevious() { return index > 0; } public int previousIndex() { return index - 1; } public int nextIndex() { return index; } public Item next() { if (!hasNext()) throw new NoSuchElementException();
  • 13. lastAccessed = current; Item item = current.item; current = current.next; index++; return item; } public Item previous() { if (!hasPrevious()) throw new NoSuchElementException(); current = current.prev; index--; lastAccessed = current; return current.item; } // replace the item of the element that was last accessed by next() or previous() // condition: no calls to remove() or add() after last call to next() or previous() public void set(Item item) { if (lastAccessed == null) throw new IllegalStateException(); lastAccessed.item = item; } // remove the element that was last accessed by next() or previous() // condition: no calls to remove() or add() after last call to next() or previous() public void remove() { if (lastAccessed == null) throw new IllegalStateException(); Node x = lastAccessed.prev; Node y = lastAccessed.next; x.next = y; y.prev = x; n--; if (current == lastAccessed) current = y; else index--; lastAccessed = null; } // add element to list public void add(Item item) {
  • 14. Node x = current.prev; Node y = new Node(); Node z = current; y.item = item; x.next = y; y.next = z; z.prev = y; y.prev = x; n++; index++; lastAccessed = null; } } public String toString() { StringBuilder s = new StringBuilder(); for (Item item : this) s.append(item + " "); return s.toString(); } // a test client public static void main(String[] args) { int n = Integer.parseInt(args[0]); // add elements 1, ..., n StdOut.println(n + " random integers between 0 and 99"); DoublyLinkedList list = new DoublyLinkedList(); for (int i = 0; i < n; i++) list.add(StdRandom.uniform(100)); StdOut.println(list); StdOut.println(); ListIterator iterator = list.iterator(); // go forwards with next() and set() StdOut.println("add 1 to each element via next() and set()"); while (iterator.hasNext()) { int x = iterator.next(); iterator.set(x + 1); }
  • 15. StdOut.println(list); StdOut.println(); // go backwards with previous() and set() StdOut.println("multiply each element by 3 via previous() and set()"); while (iterator.hasPrevious()) { int x = iterator.previous(); iterator.set(x + x + x); } StdOut.println(list); StdOut.println(); // remove all elements that are multiples of 4 via next() and remove() StdOut.println("remove elements that are a multiple of 4 via next() and remove()"); while (iterator.hasNext()) { int x = iterator.next(); if (x % 4 == 0) iterator.remove(); } StdOut.println(list); StdOut.println(); // remove all even elements via previous() and remove() StdOut.println("remove elements that are even via previous() and remove()"); while (iterator.hasPrevious()) { int x = iterator.previous(); if (x % 2 == 0) iterator.remove(); } StdOut.println(list); StdOut.println(); // add elements via next() and add() StdOut.println("add elements via next() and add()"); while (iterator.hasNext()) { int x = iterator.next(); iterator.add(x + 1); } StdOut.println(list);
  • 16. StdOut.println(); // add elements via previous() and add() StdOut.println("add elements via previous() and add()"); while (iterator.hasPrevious()) { int x = iterator.previous(); iterator.add(x * 10); iterator.previous(); } StdOut.println(list); StdOut.println(); } }