算法学习笔记:自建集合数据类型(2),使用链表实现下压栈

链表是一种递归数据结构,它或者为空,或含有泛型元素的节点和指向另一节点的引用

通过嵌套类实现链表

private class Node {
		Item item;
		Node next;
}

Node作为链表中一个元素,保存一个泛型数据和下一个链表的引用。用例不会用到单独Node,因而设为private

通过new Node() 构造函数创建Node对象,调用结果是一个指向Node对象引用,实例变量初始为null。

通过把一个Node的next指向下一个元素可以实现链表,最后一个Node的next为null。

Node first = new Node();
Node second = new Node();
Node third = new Node();
first.item = "a";
second.item = "b";
third item = "c";
first.next = second;
second.next = third;

在表头插入节点:
把first临时保存,新建一个节点赋予first,其next值设置为原来的首节点,用时O(1)

在表头删除节点
把first指向first.next。原来的first节点因为没有引用,会被自动回收,用时O(1)

在表尾插入节点
保存指向尾节点的链接last,创建新的尾节点,把原来尾节点指向新节点,用时O(1)

其他位置的增删
想要快速实现需要双向链表,这里暂时不讨论

链表栈的push方法首先保存原来的first,然后把first设定为新加入的node,并把该node的next指向原来的first

public void push(Item item) {
		Node oldNode = first;
		first = new Node();
		first.item = item;
		first.next = oldNode;
		n++;
}

pop方法先保存现在的first,然后把first设置为first.next。 返回保存的first

	public Item pop() {
		Item element = first.item;
		first = first.next;
		n--;
		return element;
	}

实现迭代器功能和之前的文章:使用数组实现下压栈 一样
https://blog.csdn.net/Raine_Yang/article/details/119923848

完整代码及测试用例:

import java.util.Iterator;

public class LinkedListStack<Item> implements Iterable<Item> {

	private class Node {
		Item item;
		Node next;
	}
	
	private int n = 0;	//the length of stack
	private Node first;
	
	public boolean isEmpty() {
		return n == 0;
	}
	
	
	public int size() {
		return n;
	}
	
	
	public void push(Item item) {
		Node oldNode = first;
		first = new Node();
		first.item = item;
		first.next = oldNode;
		n++;
	}
	
	
	public Item pop() {
		Item element = first.item;
		first = first.next;
		n--;
		return element;
	}
	
	
	public Iterator<Item> iterator() {
		return new ReverseLinkedListIterator();
	}
	
	
	private class ReverseLinkedListIterator implements Iterator<Item> {
		private Node current = first;
		public boolean hasNext() {
			return current != null;
		}
		public Item next() {
			Item item = current.item;
			current = current.next;
			return item;
		}
		public void remove() {
			// leave blank on purpose
		}
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		LinkedListStack<Integer> test = new LinkedListStack<Integer>();
		test.push(1);
		test.push(2);
		test.push(3);
		test.push(4);
		test.push(5);
		test.pop();
		test.pop();
		test.pop();
		System.out.println(test.pop());
		
	}

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值