zoukankan      html  css  js  c++  java
  • 链表

    public class MyLinked {
    private Node head = null;
    private Node last = null;
    private int len = 0;

    /**
    * 添加,到尾部
    *
    * @param s
    */
    public void add(String s) {
    Node n = new Node(s);
    if (head == null) {
    head = n;
    last = n;
    } else {
    last.next = n;
    last = n;
    }
    len++;

    }

    /**
    * 插入到中间
    *
    * @param s
    * @param index
    */
    public void add(String s, int index) {
    if (index < 0 || index >= len) {
    System.err.println("下标越界");
    }
    Node n = new Node(s);
    Node n1 = getNodeByIndex(index - 1);// 前一个节点
    Node n2 = getNodeByIndex(index);// 后一个节点
    if (index == 0) {
    n.next = n2;
    head = n;
    } else {
    n1.next = n;
    n.next = n2;
    }
    len++;

    }

    /**
    * 删除
    *
    * @param index
    */
    public void remove(int index) {
    if (index < 0 || index >= len) {
    System.err.println("下标越界");
    }
    Node n=getNodeByIndex(index);
    Node n1=getNodeByIndex(index-1);
    Node n2=getNodeByIndex(index+1);
    if(index==0) {
    n.next=null;
    head=n2;
    }else {
    n1.next=n2;
    n.next=null;
    }
    len--;
    }

    /**
    * 修改
    *
    * @param index
    * @param s
    */
    public void update(int index, String s) {
    Node n=getNodeByIndex(index);
    n.data=s;
    }

    /**
    * 查找栈的大小
    *
    * @return
    */
    public int size() {
    return len;
    }

    /**
    * 得到数据
    *
    * @return
    */
    public String getData(int index) {
    Node n = getNodeByIndex(index);
    if (n != null) {
    return n.data;
    }
    return null;
    }

    public Node getNodeByIndex(int index) {
    Node n = head;
    for (int i = 0; i < index; i++) {
    n = n.next;
    }
    if (n != null) {
    return n;
    }
    return null;
    }

    private class Node {
    String data; // 数据
    Node next; // 对下一个节点的引用

    public Node(String data) {
    this.data = data;
    }
    }

    }

        链表

        

         

        

          

          

          

    努力的过程中,可能会有很多的困难,但是我们要迎难而上。
  • 相关阅读:
    linux命令学习(3):ls命令
    敏捷开发 我的经验(三)运转
    敏捷开发 我的经验(二)资源计算-以人为本
    敏捷开发 我的经验(一)基本概念
    docker 搭建ntp服务器
    非程序员误入
    简单测试服务器磁盘读写速度
    搭建问题二之您添加的站点已存在
    搭建遇到问题一之安装fileinfo扩展插件失败
    简单快速搭建视频网站
  • 原文地址:https://www.cnblogs.com/Love-your-life/p/11318004.html
Copyright © 2011-2022 走看看