(九)链表—单链表

一、链表说明:

1.         链表是继数组之后的又一个使用很广泛的数据结构。链表包括有单链表、双端链表、有序链表、双向链表和有迭代器的链表等。

2.         在链表中,每个数据项在“链结点”(Link)中。每个Link对象都包含一个对下一个链结点的引用字段(通常叫做next),链表本身有一个字段指向对第一个链结点的引用。链表的结构如图所示:

 

单链表

 

二、单链表的操作:

1.         单链表包含的操作:在链表头插入一个数据项;在链表头删除一个数据项;遍历链表显示他的内容。

 

三、Java语言描述单链表:

package com.solid.link;

public class Link {

    //链结点的引用

    Link next;

    //链表中存放的数据

    int iDate;

   

    /**

     * 构造方法

     * @param iDate

     */

    public Link(int iDate) {

       this.iDate = iDate;

    }

   

    /**

     * 显示链结点元素

     */

    public void display() {

       System.out.print("{" + iDate + "}");

    }

}

 

package com.solid.link;

public class LinkList {

    //对第一个链结点的引用

    Link first;

   

    /**

     * 链表的构造方法

     */

    public LinkList() {

       first = null;

    }

   

    /**

     * 链表首部插入一个元素

     * @param iDate

     */

    public void insertFirst(int iDate) {

       Link link = new Link(iDate);

       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.iDate != 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.iDate != 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;

    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值