链表实现栈
链表也可以实现栈,通过在表头插入元素的方式实现push操作,删除链表的表头结点的方式实现pop操作

链表结构
/**
* 单向链表
*/
public class ListNode {
private int data;
private ListNode next;
public ListNode(int data) {
this.data = data;
}
public void setData(int data) {
this.data = data;
}
public int getData() {
return this.data;
}
public void setNext(ListNode next) {
this.next = next;
}
public ListNode getNext() {
return this.next;
}
}
链表的栈实现
/**
* 基于链表的栈的实现
*/
public class LinkedListStack {
private ListNode head = null;
public LinkedListStack() {
head = new ListNode(0);
}
public void Push(int data) {
if (head == null) {
head = new ListNode(data);
} else if (head.getData() == 0) {
head.setData(data);
} else {
ListNode node = new ListNode(data);
node.setNext(head);
head = node;
}
}
public int pop() {
if (head == null) {
throw new EmptyStackException();
} else {
int data = head.getData();
head = head.getNext();
return data;
}
}
public int top() {
if (head == null) {
return 0;
} else {
return head.getData();
}
}
public boolean isEmpty() {
return head == null;
}
public void deleteStack() {
head = null;
}
}
本文介绍了一种使用链表实现栈的数据结构方法。通过在链表头部插入元素来完成push操作,删除链表头部节点实现pop操作。文章详细展示了链表节点的定义及基于链表的栈的具体实现。
&spm=1001.2101.3001.5002&articleId=108392768&d=1&t=3&u=fef8de25483b48da8aa9cf179083903d)
363

被折叠的 条评论
为什么被折叠?



