结合下面的代码看java
class Node { private Node next;//存放结点的变量 private int data;//存放数据的变量 public Node(int data) { this.data = data; } public Node getNext() { return next; } public void setNext(Node next) { this.next = next; } public int getData() { return data; } public void setData(int data) { this.data = data; } }
LinkListnode
class LinkList { private Node first; private int size = 0;// 节点的位置 public void addFirst(int data) { Node node = new Node(data); node.setNext(first); first = node; size++; } public void add(int index, int data) { //判断index是否符合条件 if (index < 0) { throw new IllegalArgumentException("非法参数:" + index); } if (index > size()) { throw new IndexOutOfBoundsException(); } if (index == 0) { addFirst(data); size++; return; } Node temp = first; int length = 0; //获取指定索引上的Node,将上一个Node的next记录下来,更改上一个Node的next while (temp.getNext() != null) { if (index - 1 == length) { Node node = new Node(data); Node tempNode = temp.getNext(); temp.setNext(node); node.setNext(tempNode); size++; return; } length++; temp = temp.getNext(); } } public int size() { /*int length = 0; if (first != null) { length++; } else { return length; } Node node = first; while (node.getNext() != null) { length++; node = node.getNext(); } return length;*/ return size; } public Object get(int index) { //判断index是否符合条件 if (index < 0) { throw new IllegalArgumentException("非法参数:" + index); } if (index > size()) { throw new IndexOutOfBoundsException(); } Node temp = first; //获取指定索引上的Node,将上一个Node的next记录下来,更改上一个Node的next for (int i = 0; i < index; i++) { temp = temp.getNext(); } return temp.getData(); } }