Java数据结构与算法

来源:互联网 发布:拍拍贷网络最新黑名单 编辑:程序博客网 时间:2024/05/21 09:30

链表是继数组之后,使用的最广泛的通用存储结构,它也可以取代数组作为其他存储结构的基础例如栈,队列。常见链表包括单链表,双端链表,有序链表,双向链表。


1. 单链表

1.1 节点类

链表的数据都放在节点中,每个节点存放当前节点的数据(可能不止一种数据),以及对下一个节点的引用。对于Java而言,通常使用一个Link节点类来表示节点,类中通常包含:当前节点的数据变量,对下一个节点的引用next字段

class Link {public int iData;public double dData;public Link next;// 创建节点public Link(int id, double height) {iData = id;dData = height;next = null;}}


1.2. 链表类

链表类唯一的数据成员就是:Node head - 头结点;实现的函数有:从头结点插入节点,从头结点删除节点,查找数据(返回节点),打印链表。

1.2.1 插入节点

单链表节点从头结点插入:将head所指节点赋给被插入节点.next;再将被插入节点赋给head。

// 从表头插入数据public void insert(int age) {Node newNode = new Node(age);newNode.next = head;head = newNode;}

1.2.2 删除节点

单链表从头结点删除节点:将head指向head.next。

// 从表头删除数据public void delete() {head = head.next;}

1.2.3 查找数据

注意引入一个temp节点 - current。

// 查找数据public Node find(int number){Node current = head;while (current != null) {if (current.age == number) {return current;}current = current.next;}return null;}

1.2.4 打印链表

// 打印链表public void print() {Node current = head;while (current != null) {System.out.print(current.age + " ");current = current.next;}System.out.println("");}


3. 双端链表

双端链表就是在单向链表的基础上,在class LinkList中多添加一个Node tail,表示尾节点。这样可以对整个链表首尾同时进行操作。

class LinkList {Node head;Node tail;// others function}

4. 有序链表

链表中的数据是有序的。


5. 双向链表

单链表只能按照一个顺序遍历,无法反向遍历,双向链表可以逆向遍历。


6. 链表的优缺点

1)插入,删除速度快,因为插入删除不需要像链表那样移动数据。

2)链表容易扩展内存,而数组大小固定。




原创粉丝点击