public class Linked {
private Node head;
private Node last;
private int size;
public Linked(){
size = 0;
}
public Linked(Node head,Node last){
this.head = head;
this.last = last;
head.next = last;
size = 2;
}
public void insert(Node node,int index)throws Exception{
if (index<0||index>size){
throw new Exception("链表越界");
}
//如果还没有初始化
if (size == 0){
this.head = node;
this.last = node;
}
//插在尾部
else if (index==size){
last.next = node;
last = last.next;
}
//插在头部
else if (index == 0){
node.next = head;
head = node;
}
//插在中间
else{
node.next = getNode(index-1).next;
getNode(index-1).next = node;
}
size++;
}
public void delete(int index)throws Exception{
if (index<0||index>size){
throw new Exception("链表越界");
}
if (index == 0){
head = head.next;
}
else if (index == size-1) {
getNode(index - 1).next = null;
last = getNode(index - 1);
}
else{
getNode(index-1).next = getNode(index).next;
}
size--;
}
public Node getNode(int index){
int i = 0;
Node n1 = head;
while(true){
if (i == index){
return n1;
}
n1 = n1.next;
i++;
}
}
public void update(int index,String date){
getNode(index).date = date;
}
public void output(){
Node n1 = head;
for (int i = 0; i < size; i++) {
System.out.println(n1+" ");
n1 = n1.next;
}
}
public static void main(String[] args)throws Exception {
Node n1 = new Node("1号");
Node n2 = new Node("2号");
Node n3 = new Node("3号");
Node n4 = new Node("4号");
Node n5 = new Node("5号");
Node n6 = new Node("6号");
Linked linked1 = new Linked(n1, n5);
linked1.insert(n2,1);
linked1.insert(n3,2);
linked1.insert(n4,3);
linked1.insert(n6,0);
linked1.update(0,"0号");
linked1.output();
linked1.delete(0);
linked1.delete(2);
linked1.delete(3);
linked1.output();
}
}
class Node{
String date;
Node next;
public Node(){}
public Node(String date,Node next){
this.date = date;
this.next = next;
}
public Node(String date){
this.date = date;
}
@Override
public String toString() {
return date;
}
}
链表的增删改查(Java编程)
于 2022-02-13 20:53:25 首次发布