数据结构
我们知道,在数据结构中,有逻辑关系和物理关系:
逻辑关系:人为认为
- 集合:在一个范围内有多个数据,这多个数据相互没有练习
- 线性:一对一
- 树形:一对多
- 图:多对多
物理关系:内存存储
- 顺序存储:数组
- 链式存储:链表
LinkedList的实现
Linked是依靠一个Node类型的节点来存储它下一个节点的引用和本节点的数值
package com.tangbaobao.LinkedList;
/**
* 链表的节点
*
* @author 唐学俊
* @create 2018/03/10
**/
public class Node {
private Object value;
private Node nextNode;
public Node(Object value) {
this.value = value;
}
public Object getValue() {
return value;
}
public void setValue(Object value) {
this.value = value;
}
public Node getNextNode() {
return nextNode;
}
public void setNextNode(Node nextNode) {
this.nextNode = nextNode;
}
}
package com.tangbaobao.LinkedList;
/**
* 用来操作LinkedList算法类
*
* @author 唐学俊
* @create 2018/03/10
**/
public class MyLinkedList {
private Node head = null;
private int size = 0;
public int size() {
return size;
}
/**
* 添加
*
* @param value
*/
public void add(Object value) {
//初始化链表
Node newNode = new Node(value);
if (head == null) {//第一次添加
head = newNode;
} else {
//定义一个向后移动的指针
Node temp = head;
while (temp.getNextNode() != null) {
temp = temp.getNextNode();//节点向后移动
}
//循环结束,temp代表最后一个节点
temp.setNextNode(newNode);
}
size++;
}
/**
* 获取linked中的值
*
* @param index
* @return
*/
public Object get(int index) {
Node temp = head;
//一直循环到索引的位置
for (int i = 0; i < index; i++) {
temp = temp.getNextNode();
}
return temp.getValue();
}
/**
* 修改Linked中元素
*
* @param index
* @param value
*/
public void set(int index, Object value) {
Node temp = head;
for (int i = 0; i < index; i++) {
temp = temp.getNextNode();
}
temp.setValue(value);
}
/**
* 清除链表
*/
public void clear() {
head = null;
size = 0;
}
public void removeAt(int index) {
//删除头节点
if (index == 0) {
head = head.getNextNode();
} else {
Node temp = head;
for (int i = 0; i < index - 1; i++) {
temp = temp.getNextNode();
}
//将目标元素的前一个元素的nextNode存入目标元素的下一个引用
temp.setNextNode(temp.getNextNode().getNextNode());
}
size--;
}
}
package com.tangbaobao.LinkedList;
import org.junit.Test;
/**
* 测试类
*
* @author 唐学俊
* @create 2018/03/10
**/
public class TestDemo {
@Test
public void fun1(){
MyLinkedList list = new MyLinkedList();
list.add(1);
list.add(5);
list.add(8);
list.add(9);
list.add(15);
list.add(0);
list.set(2,"a");
// list.clear();
list.removeAt(2);
for (int i = 0; i < list.size(); i++) {
Object o = list.get(i);
System.out.println(o);
}
}
}