package com.linear.stack;
/**
* @author wangcong
* @date 2021/12/18 19:56:54
* @update 2021/12/18 19:56
*/
public class DummyLinked<T> {
private class Node{
private T ele;
private Node next;
public Node(T t,Node next) {
this.ele = t;
this.next = next;
}
public Node(T t){
this(t,null);
}
}
private int size; //链表元素个数
private Node dummy; //链表的虚拟头结点
public DummyLinked(){
dummy = new Node(null,null);
this.size = 0;
}
//获取链表元素的个数
public int getSize(){
return this.size;
}
//判断链表是否为空
public boolean isEmpty(){
return this.size == 0;
}
//向链表中间插入元素
public void add(T ele,int index){
if (index <0 || index >size){
throw new IllegalArgumentException("index is error");
}
Node preNode = this.dummy;
//找到要插入节点的前一个节点
for(int i = 0; i < index; i++){
preNode = preNode.next;
}
Node node = new Node(ele);
//要插入的节点的下一个节点指向preNode节点的下一个节点
node.next = preNode.next;
//preNode的下一个节点指向要插入节点node
preNode.next = node;
this.size++;
}
//链表头部添加元素
public void addFirst(T ele){
this.add(ele, 0);
}
//向链表尾部插入元素
public void addLast(T ele){
this.add(ele, this.size);
}
//获取链表index位置的元素
public T get(int index){
if (index < 0 || index >= this.size){
throw new IllegalArgumentException("index is error");
}
Node node = this.dummy.next;
for(int i=0; i < index; i++){
node = node.next;
}
return node.ele;
}
//获取链表的第一个元素
public T getFirst(){
return this.get(0);
}
//获取链表最后一个元素
public T getLast(){
return this.get(this.size-1);
}
//修改链表第index位置上的元素
public void set(T ele, int index){
if (index < 0 || index >= this.size){
throw new IllegalArgumentException("set index is error");
}
Node node = this.dummy.next;
for(int i = 0; i < index; i++){
node = node.next;
}
node.ele = ele;
}
//判断链表是否包含某元素
public boolean isContain(T ele){
Node cur = this.dummy.next;
while(cur != null){
if (cur.ele.equals(ele)){
return true;
}
cur = cur.next;
}
return false;
}
//删除链表index位置上的元素,并且返回删除元素
public T remove(int index){
Node pre = this.dummy;
for (int i = 0; i < index; i++){
pre = pre.next;
}
Node delNode = pre.next;
pre.next = delNode.next;
delNode.next = null;
this.size--;
return delNode.ele;
}
//删除链表的第一个元素
public T removeFirst(){
return this.remove(0);
}
//删除链表的最后一个元素
public T removeLast(){
return this.remove(this.size-1);
}
@Override
public String toString() {
StringBuffer sb = new StringBuffer();
Node cur = this.dummy.next;
while (cur != null){
sb.append(cur.ele+"->");
cur = cur.next;
}
sb.append("NULL");
return sb.toString();
}
}
测试代码:
package com.linear.stack;
/**
* 单链表实现栈的测试
* @author wangcong
* @date 2021/12/18 19:28:18
* @update 2021/12/18 19:28
*/
public class LinkedStackTest {
public static void main(String[] args) {
DummyLinked<Integer> stack = new DummyLinked<>();
for (int i =0; i < 5; i++){
stack.addFirst(i);
}
System.out.println(stack);
System.out.println("栈顶元素:"+stack.removeFirst());
System.out.println(stack);
System.out.println("栈顶元素:"+stack.getFirst());
}
}
三、栈---单链表模拟栈
最新推荐文章于 2024-06-16 00:05:12 发布