zoukankan      html  css  js  c++  java
  • 单链表

    public class Element {
    public Object object;
    public Element next = null;

    public Element(Object object){
    this.object = object;
    }
    }
    public class SingleLinkList {
    private Element element;

    public void init(){
    element = new Element(null);
    element.next = null;
    }

    public void add(int data){
    Element node = new Element(data);
    Element tmp = element;
    while (tmp.next != null){
    tmp=tmp.next;
    }
    tmp.next = node;
    }

    public void delete(Object value){
    Element tmp = element;
    //找到删除元素的上一个节点,在进行删除
    while (tmp.next.object != value){
    tmp = tmp.next;
    }
    tmp.next = tmp.next.next;
    //删除的是下一个节点
    /*while (tmp.next != null){
    if(tmp.object == value){
    tmp.next = tmp.next.next;
    return;
    }
    tmp = tmp.next;
    }*/
    }

    public int length(){
    Element tmp = element;
    int i=0;
    while (tmp.next != null){
    tmp = tmp.next;
    i++;
    }
    return i;
    }

    public void display(){
    Element tmp = element.next;
    while (tmp != null){
    System.out.println("链表的值:" + tmp.object);
    tmp = tmp.next;
    }
    }
    }
    public class Demo {
    public static void main(String[] args){
    SingleLinkList sll = new SingleLinkList();
    sll.init();
    sll.add(1);
    sll.add(2);
    sll.add(3);
    sll.add(4);
    sll.add(5);
    sll.display();
    System.out.println("链表的长度为:" + sll.length());
    System.out.println("---------------删除元素----------------------");
    sll.delete(2);
    sll.display();
    System.out.println("链表的长度为:" + sll.length());
    }
    }
  • 相关阅读:
    [原]Android 开发第一步
    [转]使用Android-Studio 开发Android 程序
    [转]VS2010 常用插件
    [转]FluentData
    BUUCTF-[HCTF 2018]WarmUp
    2019.11.11读书笔记
    2019.11.9读书笔记
    记录一道神仙CTF-wtf.sh-150
    SDOI2018 一轮培训划水祭
    [SHOI2009]会场预约
  • 原文地址:https://www.cnblogs.com/mutong1228/p/10759752.html
Copyright © 2011-2022 走看看