提交 b6507b6e 编写于 作者: 武汉红喜's avatar 武汉红喜

collections

上级 7c60e953
package org.hongxi.java.util.collections;
/**
* @author shenhongxi 2019/8/12
*/
public class ListReverseTest {
public static void main(String[] args) {
SimpleList<Integer> list = new SimpleList<>();
list.add(1);
list.add(2);
list.add(3);
System.out.println(list);
list.reverse();
System.out.println(list);
}
}
package org.hongxi.java.util.collections;
/**
* @author shenhongxi 2019/8/12
*
* @see java.util.LinkedList
*/
public class SimpleList<E> {
int size;
Node<E> first;
Node<E> last;
void add(E e) {
final Node<E> l = last;
final Node<E> newNode = new Node<>(e, null);
last = newNode;
if (l == null)
first = newNode;
else
l.next = newNode;
size++;
}
void reverse() {
if (first == null) return;
last = first;
Node<E> pre = first;
Node<E> curr = pre.next;
while (curr != null) {
pre.next = curr.next;
curr.next = first;
first = curr;
curr = pre.next;
}
}
static class Node<E> {
E item;
Node<E> next;
Node(E item, Node<E> next) {
this.item = item;
this.next = next;
}
}
@Override
public String toString() {
StringBuilder s = new StringBuilder();
for (Node<E> p = first; p != null; p = p.next) {
s.append(p.item);
if (p != last) {
s.append(", ");
}
}
return "[" + s.toString() + "]";
}
}
package org.hongxi.java.util.collections;
import java.util.ArrayList;
import java.util.EmptyStackException;
import java.util.List;
/**
* @author shenhongxi 2019/8/12
*
* @see java.util.Stack
*/
public class SimpleStack<E> {
private int size;
private List<E> elements = new ArrayList<>();
public void push(E ele) {
if (elements.size() > size) {
elements.set(size, ele);
} else {
elements.add(ele);
}
size++;
}
public E pop() {
if (size == 0) {
throw new EmptyStackException();
}
return elements.set(--size, null);
}
public int size() {
return size;
}
}
package org.hongxi.java.util.collections;
/**
* @author shenhongxi 2019/8/12
*/
public class StackTest {
public static void main(String[] args) {
SimpleStack<Integer> stack = new SimpleStack<>();
stack.push(1);
stack.push(2);
stack.push(3);
System.out.println(stack.pop());
System.out.println(stack.pop());
System.out.println(stack.pop());
}
}
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册