Implement Double Linked List from Stack

   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();

	}
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值