Other articles:
Java array emulation stack
Use of the Java stack
What is the stack above 2 articles said many times, a sentence summary: stack follows the principle of first in last out
Add elements
Single linked list add delete change check
Just move to the very end and then temp. Next = heroNode; Can be
Pop-up element
Using a linked list to pop an element, you only need to pop the last element
When the last element is popped, go to the position before the element to be deleted, and then temp.next = null
Linked list node class
This node is not too difficult, very common a node class
public class HeroNode4 {
int id;
String name;
HeroNode4 next;
public HeroNode4(int id, String name) {
this.id = id;
this.name = name;
}
@Override
public String toString(a) {
return "HeroNode4{" +
"id=" + id +
", name='" + name + '\' ' +
'} '; }}Copy the code
Complete code:
public class StackLinkedList {
private final HeroNode4 head = new HeroNode4(0."");
// Add elements
public void push(HeroNode4 heroNode) {
HeroNode4 temp = head;
while(temp.next ! =null) {
temp = temp.next;
}
temp.next = heroNode;
}
// Pop up elements
public void pop(a) {
if (head.next == null) {
throw new RuntimeException("Pop: No data in linked list, can't pop");
}
HeroNode4 temp = head;
while(temp.next.next ! =null) {
temp = temp.next;
}
temp.next = null;
}
// Outputs all elements
public void show(a) {
if (head.next == null) {
System.out.println("Show: Linked list null, cannot print");
return;
}
HeroNode4 temp = head;
Stack<HeroNode4> stack = new Stack<>();
while(temp.next ! =null) {
temp = temp.next;
stack.push(temp);
}
// Check whether the stack is empty or not
while(! stack.empty()) { System.out.println("show:"+ stack.pop()); }}}Copy the code
Test code:
public static void main(String[] args) {
StackLinkedList stackLinkedList = new StackLinkedList();
// Add elements
stackLinkedList.push(new HeroNode4(1."Sung river"));
stackLinkedList.push(new HeroNode4(2."Wong Fei Hung"));
stackLinkedList.push(new HeroNode4(3."李逵"));
stackLinkedList.push(new HeroNode4(4."Charlie"));
try {
// Pop up elements
stackLinkedList.pop();
stackLinkedList.pop();
// stackLinkedList.pop();
// stackLinkedList.pop();
// stackLinkedList.pop();
} catch (Exception e) {
System.out.println(e.getMessage());
}
stackLinkedList.show();
}
Copy the code
The running results are as follows:
show:HeroNode4{id=2, name='Wong Fei Hung'}
show:HeroNode4{id=1, name='sung river'}
Copy the code
The complete code
The complete code
What do you like?
Java data structures and algorithms directory
Original is not easy, your praise is the biggest support for me!