温习Algs4 (一):背包, 栈, 队列和线性表

这篇博客主要介绍了四种基础数据结构:背包、栈、队列和线性表。对于每种结构,详细讲解了其功能和内部实现,如背包的添加和遍历,栈的压栈、出栈等操作,队列的入列、出列,以及线性表的动态数组实现。此外,还分析了各种操作的时间复杂度。
摘要由CSDN通过智能技术生成

背包

背包是最简单的数据结构, 只有添加数据遍历元素两个功能, 内部实现是链表.

Bag.java

/******************************************************************************
 *  Compilation:  javac Bag.java
 *  Execution:    java Bag
 *  Author:       Chenghao Wang
 ******************************************************************************/

import java.util.Iterator;
import java.util.NoSuchElementException;

public class Bag<T> implements Iterable<T> {
   

    private class Node {
   
        private T item;
        private Node next;

        Node(T item) {
   
            this.item = item;
            next = null;
        }
    }

    private class BagIterator implements Iterator<T> {
   

        private Node current = head;

        @Override
        public boolean hasNext() {
   
            return current != null;
        }

        @Override
        public T next() {
   
            if (current == null) throw new NoSuchElementException();
            T result = current.item;
            current = current.next;
            return result;
        }

        @Override
        public void remove() {
   
            throw new UnsupportedOperationException();
        }
    }

    private Node head = null;

    public void add(T item) {
   
        Node n = new Node(item);
        n.next = head;
        head = n;
    }

    @Override
    public Iterator<T> iterator() {
   
        return new BagIterator();
    }
}

复杂度分析

  • add: O(1)

栈支持的功能有压栈, 出栈, 查询栈顶元素, 检查是否为空和查询元素个数. 内部实现也是链表.

Stack.java

/******************************************************************************
 *  Compilation:  javac Stack.java
 *  Execution:    java Stack
 *  Author:       Chenghao Wang
 ******************************************************************************/

import java.util.Iterator;
import java.util.NoSuchElementException;

public class Stack<T> implements Iterable<T> {
   

    private class Node {
   
        private T item;
        private Node next;

        Node(T item) {
   
            this.item = item;
            next = null;
        }
    }

    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值