StackDLink 双向链表

LinkedStack实现的双向链表,功能与DLink一致

就实现的难度来看:

addFirst,addLast,removeFirst,removeLast,next,preivous,hasNext,hasPrevious比DLink简单

但是insertBefore,insertAfter,removeBefore,removeAfter比较困难。

另外indexOf不易实现,没有做

class StackDLink {
	private LinkedStack nextStack = new LinkedStack();
	private LinkedStack previousStack = new LinkedStack();
	private boolean direction = true;
	private int length;

	void addFirst(int value) {
		turn(true);
		nextStack.push(value);
		length++;
	}

	void addLast(int value) {
		turn(false);
		previousStack.push(value);
		length++;
	}


	int removeFirst() {
		turn(true);
		if(nextStack.isEmpty()) return -1;
		length--;
		return nextStack.pop();
	}

	int removeLast() {
		turn(false);
		if(previousStack.isEmpty()) return -1;
		length--;
		return previousStack.pop();
	}

	int getLength() {
		return length;
	}

	boolean hasNext() {
		return !nextStack.isEmpty();
	}

	int next() {
		if(!direction)previousStack.push(nextStack.pop());
		direction = true;
		int result = nextStack.pop();
		previousStack.push(result);
		return result;
	}

	void resetBeforeFirst() {
		turn(true);
	}

	boolean hasPrevious() {
		return !previousStack.isEmpty();
	}

	int previous() {
		if(direction) nextStack.push(previousStack.pop());
		direction = false;
		int result = previousStack.pop();
		nextStack.push(result);
		return result;
	}

	void resetAfterLast() {
		turn(false);	
	}

	int removeBefore() {
		if(previousStack.isEmpty()) return -1;
		if(!direction) {
			length--;
			return previousStack.pop();
		} else {
			int temp = previousStack.pop();
			if(previousStack.isEmpty()) {
				previousStack.push(temp);
				return -1;
			}
			int result = previousStack.pop();
			length--;
			previousStack.push(temp);
			return result; 
		}
	}

	int removeAfter() {
		if(nextStack.isEmpty()) return -1;
		if(direction) {
			length--;
			return nextStack.pop();
		} else {
			int temp = nextStack.pop();
			if(nextStack.isEmpty()) {
				nextStack.push(temp);
				return -1;
			}
			int result = nextStack.pop();
			length--;
			nextStack.push(temp);
			return result; 
		}
	}

	void insertBefore(int value) {
		if(!direction || previousStack.isEmpty())previousStack.push(value);
		else {
			int temp = previousStack.pop();
			previousStack.push(value);
			previousStack.push(temp);
		}
		length++;
	}

	void insertAfter(int value) {
		if(direction || nextStack.isEmpty())nextStack.push(value);
		else {
			int temp = nextStack.pop();
			nextStack.push(value);
			nextStack.push(temp);
		}
		length++;
	}
	
	private void turn(boolean direction) {
		if(direction) {
			while(!previousStack.isEmpty()) {
				nextStack.push(previousStack.pop());
			}
		} else {
			while(!nextStack.isEmpty()) {
				previousStack.push(nextStack.pop());
			}
		}
		this.direction = direction;
	}

}  
 

 

你可能感兴趣的:(stack)