《算法》笔记:链表、栈和队列

【链表】

1.实现链表

在这里插入图片描述

public class Node
{
	Item item;//Item 表示想用的任意数据类型
	Node next;
}

2.插入结点

①表头插入:
第一步 保存好首节点
第二步 设置新结点
第三步 让保存好的首节点指向新结点

Node oldFirst = first;
first = new Node();
first.item=110;
first.next = oldfirst;

②表尾插入

Node oldLast = last;
last = new Node();
last.item=70;
oldLast.next=last;

3.删除结点

表头删除

first = first.next

4.遍历

for(Node x =first ; x!=null ; x=x.next)
 {
 //处理x.item
}

【栈、队列】

1.两者特点比较

①栈:先进先出
②队列:后进先出
在这里插入图片描述

2.栈的实现

public class Stack<Item> {
	private Node first;
	private int N;//记录栈中元素个数
	private class Node
	{
		Item item;
		Node next;
	}
	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;
	}
	public boolean isEmpty() {
		return first==null;
	}
	public int size() {
		return N;
	}
}

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 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 int size() {

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值