/**
* @author zhangshiqiang on 2020/2/28.
*/
public class LinkedStack {
private int size;
private int curSize;
private Node head;
public LinkedStack(int size) {
this.size = size;
this.curSize = 0;
head = new Node();
}
public boolean isFull() {
return curSize == size;
}
public boolean isEmpty() {
return curSize == 0;
}
public void push(Node node) {
if (isFull()) {
System.out.println("栈已满");
return;
}
curSize++;
Node cur = this.head;
while (cur.next != null) {
cur = cur.next;
}
cur.setNext(node);
}
public Node pop() {
if (isEmpty()) {
System.out.println("空栈");
return null;
}
curSize--;
Node cur = this.head;
Node pre = null;
while (cur.next != null) {
pre = cur;
cur = cur.next;
}
pre.setNext(null);
return cur;
}
public LinkedStack revers2() {
if (head.next == null) {
return this;
}
Node pre = head.next;
Node cur = pre.next;
pre.next = null;
Node tmp;
head.next = null;
while (cur != null) {
tmp = cur.next;
cur.next = pre;
pre = cur;
cur = tmp;
}
head.next = pre;
return this;
}
public LinkedStack reverse() {
Node cur = this.head;
Node newNode = new Node();
Node pre;
// 0>1>2>3>4>5
// 0>1
// 0>2>1
// 0>3>2>1
// 0>4>3>2>1
// 0>5>4>3>2>1
while (cur.next != null) {
// 第一次是 1
// 第二次是 2
pre = cur.next;
// cur还在head节点,指向2
// cur还在head节点,指向3
cur.next = cur.next.next;
if (newNode.next == null) {
pre.next = null;
newNode.next = pre;
} else {
pre.next = newNode.next;
newNode.next = pre;
}
}
setHead(newNode);
return this;
}
public void setHead(Node head) {
this.head = head;
}
private static class Node {
private int i;
private Node next;
public Node() {
}
public Node(int i) {
this.i = i;
}
public void setNext(Node next) {
this.next = next;
}
@Override
public String toString() {
return "Node{" +
"i=" + i +
'}';
}
}
public void list() {
Node cur = this.head;
while (cur.next != null) {
cur = cur.next;
System.out.println(cur);
}
}
@Override
public String toString() {
return "LinkedStack{" +
"size=" + size +
", curSize=" + curSize +
", head=" + head +
'}';
}
public static void main(String[] args) {
LinkedStack linkedStack = new LinkedStack(5);
linkedStack.push(new Node(1));
linkedStack.push(new Node(2));
linkedStack.push(new Node(3));
linkedStack.push(new Node(4));
linkedStack.push(new Node(5));
linkedStack.push(new Node(6));
linkedStack.reverse().list();
}
}