Imagine all items are organized into two stacks,one of them is head stack,and the other one is tail stack:
For Example:
head : 1,2,3,4->
tail : <-5,6,7,8
now u can move 4 to 5:
head : 3,2,1->
tail : <-4,5,6,7,8
or u can move 5 to 4;
head : 5,4,3,2,1->
tail : <-6,7,8
and them i will give the java code below this
import java.util.Stack;
class DoubleLinkedList{
Stack<Integer> s;
Stack<Integer> t;
int count;
DoubleLinkedList(){
s = new Stack<Integer>();
t = new Stack<Integer>();
count = 0;
}
// insert an data into the tail of head stack
// move all the item of head stack to tail stack and add count
public void insertInBeginning(int data){
while(!s.isEmpty()){
t.push(s.pop());
}
s.push(data);
count++;
}
// insert an data into the tail of tail stack // move all the item of tail stack to head stack and add count
public void insertAtEnd(int data){
while(!t.isEmpty()){
s.push(t.pop());
}
t.push(data);
count++;
}
// if tail stack != null ,remove the top item of tail stack,and put it into head stack
public void moveForward(){
while(!t.isEmpty()){
int temp = t.pop();
System.out.println(temp);
s.push(temp);
}
}
// if head stack!=null, remove the top item of head stack and put it into tail stack
public void moveBackward(){
while(!s.isEmpty()){
int temp = s.pop();
System.out.println(temp);
t.push(temp);
}
}
// iterat item from head to tail,first move all the item of head stack to tail stack
// and then get the top item of tail stack , if it is equal to data ,remove it,if not remove it and put it to head stack
public void delete(int data){
while(!s.isEmpty()){
t.push(s.pop());
}
while(!t.isEmpty()){
if(t.peek() == data){
t.pop();
return;
}
else{
s.push(t.pop());
}
}
}
// find out the buttom item of head stack and then remove it
public void deleteFirst(){
while(!s.isEmpty()){
int temp = s.pop();
if(s.peek() == null){
return;
}
t.push(temp);
}
}
// find out the buttom item of tail stack and then remove it
public void deleteLast(){
while(!t.isEmpty()){
int temp = t.pop();
if(t.peek() == null){
return;
}
s.push(temp);
}
}
}
class P2{ public static void main(String args[]){ DoubleLinkedList list = new DoubleLinkedList(); list.insertInBeginning(4); list.insertInBeginning(3); list.insertInBeginning(2); list.insertInBeginning(1); list.insertAtEnd(5); list.insertAtEnd(6); list.insertAtEnd(7); list.moveBackward(); list.moveForward(); list.delete(5); list.moveBackward(); list.moveForward(); } }