1.3.3链表

  1. 链表
    定义:链表是一种递归的数据结构,它或者为空(null),或者指向一个结点的引用,该结点含有一个泛型的元素和一个指向另一条链表的引用。
    使用一个嵌套类定义结点的抽象数据类型:
private class Node
{
	Item item;
	Node next;
}
  1. 算法1.2 下压堆栈(链表实现)
    可以处理任意的数据类型
    所需要的空间总是和集合的大小成正比
    操作所需要的时间总是和集合的大小没有关系
public class Stack<Item> implements Iterable{
	private Node first; //栈顶(最近添加的元素)
	private int N;		//元素数量
	private class Node{
		//定义了结点的嵌套类
		Item item;
		Node next;
	}
	public boolean isEmpty() {
		return first ==null;
	}
	public int size() {
		return N;
	}
	public void push(Item item) {
		Node  oldfirst  = first;
		first = new Node();
		first.item = item;
		first.next = oldfirst;
		N++;
	}
	public Item pop() {
		Item item = first.item;
		first = first.next;
		N--;
		return item;
	}
	
	@Override//见算法1.4
	public Iterator iterator() {
		// TODO Auto-generated method stub
		return null;
	}
	//测试用例
	public static void main (String[] arg) {
		Stack<String> S = new Stack<String>();
		Scanner sc = new Scanner(System.in);
		String str = null;
		String s = null;
		while( (str= sc.nextLine())!=null) {
			System.out.println(str);
			for(int i=0;i<str.length();i++) {
				s = String.valueOf(str.charAt(i));
				S.push(s);
			}
			for(int i=0;i<str.length();i++) {
				System.out.println(S.pop());
			}
		}
	}	
}

测试结果

  1. 算法1.3 先进先出队列
public class Queue<Item> {
	private Node first;	//指向最早添加的结点的链接
	private Node last;	//指向最近添加的结点的链接
	private int N;		//队列中元素的数量
	private class Node{
		//定义结点的嵌套类
		Item item;
		Node next;		
	}
	public boolean isEmpty() {
		return first == null;
	}
	public int size() {
		return N;
	}
	public void enqueue(Item item) {
		//向队列添加元素
		Node oldlast = last;
		last = new Node();
		last.item = item;
		last.next = null;
		if(isEmpty())
			first =last;
		else 
			oldlast.next=last;
		N++;
	}
	public Item dequeue() {
		//从表头删除数据
		Item item = first.item;
		first = first.next;
		if(isEmpty())	//判断是队列否为空
			last = null;
		N--;
		return item;
	}
	
	public static void main(String[] args) {
		Queue<String> q = new Queue<String>();
		Scanner sc = new Scanner(System.in);
		String str = null;
		String s = null;
		while((str = sc.nextLine())!=null) {
			System.out.println(str);
			for(int i = 0;i < str.length();i++) {
				s = String.valueOf(str.charAt(i));
				q.enqueue(s);
			}			
			for(int i=0;i<str.length();i++) {
				System.out.println(q.dequeue());
			}
		}
	}	
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值