学完链表和栈,数组模拟栈学完后,自己根据链表写了个链栈,虽然只是简单的实现了入栈出栈遍历。收获还是很大的。
在push这里思考了一会,思路是:传入一个数字,push里创建一个节点node,把数据加入node里,让head.next指向node(新节点),然后让node.next指向top,把node再换成top。
* * package stack; public class LinkedListStackDemo { public static void main ( String[ ] args) { SingleLinkedList singleLinkedList = new SingleLinkedList ( ) ; singleLinkedList. push ( 1 ) ; singleLinkedList. push ( 2 ) ; singleLinkedList. push ( 3 ) ; singleLinkedList. push ( 4 ) ; singleLinkedList. push ( 5 ) ; singleLinkedList. show ( ) ; singleLinkedList. pop ( ) ; singleLinkedList. pop ( ) ; singleLinkedList. pop ( ) ; }
}
class SingleLinkedList { private Node top; private static int size; public SingleLinkedList ( ) { size = 0 ; } private Node head = new Node ( ) ; public boolean isEmpty ( ) { return head. next == null; } public void push ( int data) { Node temp = new Node ( ) ; temp. setData ( data) ; head. next = temp; temp. next = top; top = temp; size++ ; } public void pop ( ) { if ( isEmpty ( ) ) { System. out. println ( "栈空" ) ; return ; } System. out. println ( "出栈的是:" + top. getData ( ) ) ; head. next = top. next; top = top. next; size-- ; } public void show ( ) { if ( isEmpty ( ) ) { System. out. println ( "栈空" ) ; return ; } Node temp = head. next; for ( int i = 1 ; i <= size; i++ ) { System. out. printf ( "栈的第 %d 个元素是:%d\n" , i, temp. getData ( ) ) ; temp = temp. next; } }
}
class Node { private int data; public Node next; public int getData ( ) { return data; } public void setData ( int data) { this . data = data; } @Override public String toString ( ) { return "Node{" + "data=" + data + '}' ; }
}
* *
结果:栈的第 1 个元素是:5
栈的第 2 个元素是:4
栈的第 3 个元素是:3
栈的第 4 个元素是:2
栈的第 5 个元素是:1
出栈的是:5
出栈的是:4
出栈的是:3