链表节点类
public class Node<E> {
private E data;
private Node<E> next;
public Node() {}
public Node(E data) {this.data = data;}
public E getData() {return data;}
public void setData(E data) {this.data = data;}
public Node<E> getNext() {return next;}
public void setNext(Node<E> next) { this.next = next;}
@Override
public String toString() {
return "Node{" +
"data=" + data +
", next=" + next +
'}';
}
}
链表的增删改查方法
package com.node;
public class SingleChainLIst<E> {
private Node<E> head;
private Node<E> last;
private int size;
private int modifiyCount;
public SingleChainLIst() {
head=new Node<E>();
last=head;
}
public int getSize(){
return size;
}
public Node<E> getHead(){
return head;
}
public Node<E> getLast(){
return last;
}
public Node<E> getNode(int index){
if(index<1||index>size){
return null;
}
Node<E> node = head.getNext();
for (int i = 1; i <index ; i++) {
node= node.getNext();
}
return node;
}
public E getValue(int index){
if(index<1||index>size){
return null;
}
Node<E> node = getNode(index);
E data = node.getData();
return data;
}
public void addNode(E e){
Node<E> node=new Node<>(e);
last.setNext(node);
last=node;
size++;
modifiyCount++;
}
public E addNode(int index,E e){
if(index<1||index>size){
return null;
}
Node<E> newNode=new Node<>(e);
Node<E> oldNode = getNode(index);
if(index==1){
head.setNext(newNode);
}else{
Node<E> preNode = getNode(index - 1);
preNode.setNext(newNode);
}
newNode.setNext(oldNode);
size++;
modifiyCount++;
return oldNode.getData();
}
public E delete(int index){
if(index<1||index>size){
return null;
}
Node<E> currentNode;
if(index==1){
currentNode = head.getNext();
head.setNext(currentNode.getNext());
currentNode.setNext(null);
}else{
Node<E> preNode = getNode(index - 1);
currentNode=getNode(index);
Node<E> nextNode = currentNode.getNext();
preNode.setNext(nextNode);
currentNode.setNext(null);
}
size--;
modifiyCount++;
return currentNode.getData();
}
public E updateNode(int index,E e){
if(index<1||index>size){
return null;
}
Node<E> node = getNode(index);
node.setData(e);
modifiyCount++;
return node.getData();
}
}
测试
public class TestChainList {
public static void main(String[] args) {
SingleChainLIst<String> chainLIst=new SingleChainLIst<>();
chainLIst.addNode("one");
chainLIst.addNode("two");
chainLIst.addNode("three");
chainLIst.addNode("four");
chainLIst.addNode("five");
}
}