package MyLinkedListDemo;
/**
* 自定义linkedList
* @author Administrator
* size 当前集合的大小
* root 根节点
*/
public class MyLinkedList {
private int size=0;
private Node root=null;
/**
* @return 集合的大小
*/
public int length() {
return size;
}
public void add(Object value) {
Node newNode =new Node(value);
//判断是否是根节点
if(root==null) {
root=newNode;
}else {//必须找到最后一个节点来添加数据
Node temp=root; //temp代表当前节点也就是指针。用了判断是否是最后一个节点
while(temp.getNext()!=null) {
temp=temp.getNext(); //让当前节点向后面移动
}
//循环结束,说明temp是最后一个节点
temp.setNext(newNode);//把新节点添加到最后面。
}
size++; //长度加1
}
public void set(int index,Object value) throws Exception{
if(index>size||index<0) {
throw new Exception("链表集合下标越界");
}
//先找到要添加数据的位置,需要先遍历集合
Node temp=root; //temp代表当前节点也就是指针。
for (int i = 0; i <index; i++) {
temp=temp.getNext();
}
//循环结束找到index的位置,添加数据。
temp.setValue(value);
}
public Object getValue(int index) throws Exception{
if(index>size||index<0) {
throw new Exception("链表集合下标越界");
}
//先找到要添加数据的位置,需要先遍历集合
Node temp=root; //temp代表当前节点也就是指针。
for (int i = 0; i <index; i++) {
temp=temp.getNext();
}
//循环结束找到index的位置,添加数据。
return temp.getValue();
}
public void clear() {
root=null;
size=0;
}
public void remove(int index)throws Exception {
if(index>size||index<0) {
throw new Exception("链表集合下标越界");
}
//获取要删除位置的下一个节点,先找到要添加数据的位置,需要先遍历集合
Node temp1=root; //temp代表当前节点也就是指针。
for (int i = 0; i <index-1; i++) {
temp1=temp1.getNext();
}
//获取要删除位置的前一个节点。
Node temp2=root; //temp代表当前节点也就是指针。
for (int i = 0; i <index; i++) {
temp2=temp2.getNext();
}
//循环结束找到index的位置,添加数据。
temp1.setNext(temp2.getNext());
size--;
}
@Override
public String toString() {
return "[" + root + "]";
}
//内部节点类
class Node{
public Object value; //节点要保存的数据
public Node next;//下一个节点的地址,也就是下一个对象的引用
//构造函数
public Node(Object value) {
this.value=value;
}
public Object getValue() {
return value;
}
public void setValue(Object value) {
this.value = value;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + getOuterType().hashCode();
result = prime * result + ((next == null) ? 0 : next.hashCode());
result = prime * result + ((value == null) ? 0 : value.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Node other = (Node) obj;
if (!getOuterType().equals(other.getOuterType()))
return false;
if (next == null) {
if (other.next != null)
return false;
} else if (!next.equals(other.next))
return false;
if (value == null) {
if (other.value != null)
return false;
} else if (!value.equals(other.value))
return false;
return true;
}
@Override
public String toString() {
return "" + value + "," + next + "";
}
private MyLinkedList getOuterType() {
return MyLinkedList.this;
}
}
}
手写简单模型单向LinkedList
最新推荐文章于 2024-03-13 19:09:39 发布