单链表

来源:互联网 发布:用php做99乘法表 编辑:程序博客网 时间:2024/06/06 00:27
    Java中有两种表的数据结构:ArrayList和LinkedList,其中ArrayList以数组的形式保存数据,即相邻两个元素在物理位置和逻辑位置上都相邻,LinkedList是采用链表的形式保存数据,即逻辑相邻的元素,物理位置不一定相邻,链表分为单链表、双向链表等,其中单链表是最简单的链表,下面就简单介绍一下单链表
    单链表中每个元素被称为“连接点”,连接点不仅保存了本身的数据对象,还保存的对下一个连接点的引用,这样才能使物理上不相邻的元素在逻辑上相邻。
链表结构入下图所示:

下面用Java代码实现一个简单的单链表
连接点类:
package com.yf.linkedlist;public class Link {/* * 下一个连接点的引用 */Link next;/* * 需要保存的数据 */int iData;public Link(int iData) {this.iData = iData;}/* * 用户打印每个连接点的值 */public void display(){System.out.print("["+iData+"]");}}

链表类
package com.yf.linkedlist;public class LinkList {// 对第一个链结点的引用Link first;/** * 链表的构造方法 */public LinkList() {first = null;}/** * 链表首部插入一个元素 *  * @param iData */public void insertFirst(int iData) {Link link = new Link(iData);link.next = first;first = link;}/** * 删除链表首部元素 *  * @return */public Link deleteFirst() {Link temp = first;first = first.next;return temp;}/** * 显示某个链表的所有元素 */public void display() {Link current = first;while (!(current == null)) {current.display();current = current.next;}System.out.println();}/** * 查找链表中某个特定的元素 *  * @param key * @return */public Link find(int key) {Link current = first;while (current.iData != key) {if (current.next == null) {return null;}current = current.next;}return current;}/** * 删除链表中某个特定的元素 *  * @param key * @return */public Link delete(int key) {Link current = first;Link previous = first;while (current.iData != key) {if (current.next == null) {return null;} else {previous = current;current = current.next;}}if (current == first) {first = first.next;} else {previous.next = current.next;}return current;}/* * 计算链表的长度 */public int size() {int length = 0;Link current=first;if(current==null)return 0;while(current.next!=null){++length;current=current.next;}/* * 由于While里面判断的是下一个链接点,所以总个数需加上本身的那一个 */return length+1;}}

测试类:
package com.yf.linkedlist;public class Main {/** * @param args */public static void main(String[] args) {LinkList linkList = new LinkList();System.out.println(linkList.size());for (int i = 1; i <= 10; i++) {linkList.insertFirst(i);}linkList.display();System.out.println(linkList.size());linkList.deleteFirst();System.out.println(linkList.size());linkList.display();linkList.delete(5);linkList.display();}}

输出结果如下:

0
[10][9][8][7][6][5][4][3][2][1]
10
9
[9][8][7][6][5][4][3][2][1]
[9][8][7][6][4][3][2][1]
这里有一点需要说明,该链表类删除元素时,我们之需要是该元素失去引用即可,Java垃圾回收机制会自动回收该连接点所占用的内存
原创粉丝点击