public class LinkedList {
//初始化一个头节点
private Node header = new Node(0,null,null);
/**添加一个节点
*1. 找到当前链表的最后节点
*2. 将最后这个节点的next 指向 新的节点
*/
public void add(Object data){
Node newNode = new Node(size()+1,data,null);
Node cur = header;
while (true){
//找到列表的最后
if(cur.next==null) break;
//没找到 继续便利下一个
cur = cur.next;
}
cur.next = newNode;
}
//删除一个节点
/**
* 1、找到要删除的节点
* 2、把上一个节点的next 指向 delNode.next;
* @param index
*/
public void remove(int index){
Node cur = header;
if(cur==null)
return;
while (true){
if(cur.next.index==index){
break;
}
cur = cur.next;
}
cur.next = cur.next.next;
}
//获取所有数据
public void list(){
if(header.next==null){
throw new RuntimeException("list is empty");
}
Node cur = header.next;
while (true){
if(cur==null){
break;
}
System.out.println(cur.data);
cur = cur.next;
}
}
/**
* 先找到一个节点
* @param node
* @return
*/
public boolean update(Node node){
if(header.next==null){
throw new RuntimeException("node not exist");
}
boolean flag = false;
Node cur = header;
while (true){
if (cur.index == node.index){
flag = true;
break;
}
cur = cur.next;
}
if(flag){
cur.data = node.data;
return true;
}
return false;
}
/**
* 将列表反转
* 1、遍历原有列表,将数据还存在数组中,
* 2、新建一个链表,将数组逆序便利其中
*/
public void reverse(){
if(size()>0){
Object[] data = new Object[size()];
int index = 0;
Node cur = header.next;
while (true){
if(cur==null){
break;
}
data[index] = cur.data;
index++;
cur = cur.next;
}
header = new Node(0,null,null);
for (int i = data.length-1; i >=0 ; i--) {
this.add(data[i]);
}
}
}
public int size(){
if(header.next == null)
return 0;
int size = 0;
Node cur = header;
while (cur.next!=null){
size++;
cur = cur.next;
}
return size;
}
}
class Node {
public int index;
public Object data;
public Node next;
public Node(int index, Object data, Node next) {
this.index = index;
this.data = data;
this.next = next;
}
@Override
public String toString() {
return "Node{" +
"index=" + index +
", data=" + data +
", next=" + next +
'}';
}
}
//新建一个测试实体类
public class Person {
private int no;
private String name;
public Person() {
}
public Person(int no, String name) {
this.no = no;
this.name = name;
}
public int getNo() {
return no;
}
public void setNo(int no) {
this.no = no;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Person{" +
"no=" + no +
", name='" + name + '\'' +
'}';
}
}
//测试类