LinkedList测试

通过DeBug测试成功,数据可以存进去

args = {String[0]@489} ml = {MyLinkedList@488} first = {Node@490} Method threw 'java.lang.StackOverflowError' exception. Cannot evaluate com.wangg.Node.toString() pre = null obj = "aa" value = {char[2]@505} hash = 0 next = {Node@494} Method threw 'java.lang.StackOverflowError' exception. Cannot evaluate com.wangg.Node.toString() pre = {Node@490} Method threw 'java.lang.StackOverflowError' exception. Cannot evaluate com.wangg.Node.toString() obj = "bb" next = {Node@491} Method threw 'java.lang.StackOverflowError' exception. Cannot evaluate com.wangg.Node.toString() last = {Node@491} Method threw 'java.lang.StackOverflowError' exception. Cannot evaluate com.wangg.Node.toString() pre = {Node@494} Method threw 'java.lang.StackOverflowError' exception. Cannot evaluate com.wangg.Node.toString() obj = "cc" next = null count = 3

package com.wangg;

public class MyLinkedList {
  //链中一定有一个首节点:
  Node first;
  //链中一定有一个尾结点:
  Node last;
  //计数器
  int count = 0;
  //提供一个构造器
  public MyLinkedList(){

  }
  //添加元素方法
  public void add(Object o){
      if (first == null){//证明你添加的是第一个节点
          //将添加的元素封装成一个Node对象
          Node node = new Node();
          node.setPre(null);
          node.setObj(o);
          node.setNext(null);
          //当前链接中要第一个节点变为node
          first = node;
          //当前链接最后一个节点变为node
          last = node;
      }else {//证明已经不是链中的第一个节点了
            //将添加的元素封装成一个Node对象
          Node node = new Node();
          node.setPre(last);//Node的上一个节点一定是当前链中的最后一个节点last
          node.setObj(o);
          node.setNext(null);
          //当前链的中的最后一个节点的下一个元素要指向,node
          last.setNext(node);
          //将最后一个节点变为node
          last = node;


      }
      //链中元素数量+1
      count++;


  }
  //得到集合中元素的数量
  public int getSize(){
      return count;
  }
  public Object get(int intdx){
      //获取链表的首元素
      Node node = first;
      for (int i = 0;i < intdx;i++){
          //一路next得到想要的元素
          node = node.getNext();
      }
      return node.getObj();
  }
}
class Test01{

  public static void main (String[]args) {
      //创建一个MyLinkedList集合对象:
      MyLinkedList ml = new MyLinkedList();
      ml.add("aa");
      ml.add("bb");
      ml.add("cc");
      System.out.println(ml.getSize());
      System.out.println(ml.get(1));
  }
}
posted @ 2021-08-15 13:48  πππ·  阅读(109)  评论(0)    收藏  举报