1、创建节点信息:
// 创建节点:
class Node{
int num; // 该节点的数据信息
Node next; // 指向下一个结点的指针
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
public Node(int num){
this.num = num;
}
}
2、增加栈的节点信息:
// 增加结点
public void push(Node node){
// 增加一个辅助变量
Node temp = null;
temp = node;
temp.setNext(rear);
rear = temp;
}
3、遍历链表栈
// 遍历所有的节点信息
public void list(){
// 创建一个辅助节点信息
Node temp = rear;
while(temp != first){
System.out.printf("%s\t",temp.num);
temp = temp.getNext();
}
}
4、弹出栈
// 弹出栈
public int pop(){
// 创建一个辅助节点
Node temp = rear;
if(temp == first){
throw new RuntimeException("此时栈为空!");
}
int value = temp.num;
temp = temp.getNext();
rear = temp;
return value;
}
5、所有的代码:
package com.LinklistStack;
import java.util.List;
public class LinkList {
public static void main(String[] args) {
Node n1 = new Node(1);
Node n2 = new Node(2);
Node n3 = new Node(3);
Node n4 = new Node(4);
Node n5 = new Node(5);
LinkedListDemo linked = new LinkedListDemo();
linked.push(n1);
linked.push(n2);
linked.push(n3);
linked.push(n4);
linked.push(n5);
linked.list();
int i1 = linked.pop();
int i2 = linked.pop();
int i3 = linked.pop();
int i4 = linked.pop();
int i5 = linked.pop();
System.out.println("\n弹出的顺序:" + i1 + "," + i2 + "," + i3 + "," + i4 + "," + i5 + "");
}
}
class LinkedListDemo{
private Node first = null;
private Node rear = first; // 头节点
// 增加结点
public void push(Node node){
// 增加一个辅助变量
Node temp = null;
temp = node;
temp.setNext(rear);
rear = temp;
}
//
// 遍历所有的节点信息
public void list(){
// 创建一个辅助节点信息
Node temp = rear;
while(temp != first){
System.out.printf("%s\t",temp.num);
temp = temp.getNext();
}
}
public int pop(){
// 创建一个辅助节点
Node temp = rear;
if(temp == first){
throw new RuntimeException("此时栈为空!");
}
int value = temp.num;
temp = temp.getNext();
rear = temp;
return value;
}
}
// 创建节点:
class Node{
int num; // 该节点的数据信息
Node next; // 指向下一个结点的指针
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
public Node(int num){
this.num = num;
}
}