今天亲手写了一次单链表的增删查功能,实现了~
package link;
/*
* 实现一个单链表的增删查改
*/
class Node<E>{
Node<E>next;
E data;
public Node(E data){this.data=data;}
public void display(){
System.out.print(data+" ");
}
}
public class LearnLink<E> {
Node<E>head=null;
int pos=0;
/*增加一个头结点*/
public void addFirstNode(E data){
Node<E>node=new Node<E>(data);
node.next=head;
head=node;
}
/*向索引为index处增加一个新的数据*/
public void addItemtoIndex(int index,E data){
Node<E>node=new Node<E>(data);
Node<E> current=head;
Node<E> previous=head;//两个指针都是从头结点开始
while(pos!=index){
previous=current; //当前结点比previous几点快一步
current=current.next;
pos++;
}
node.next=current;
previous.next=node; //插入node结点到current和previous之间
pos=0;
}
/*直接向链表中添加一个值*/
public void addDatatoLink(E data){
Node<E> node=new Node<E>(data);
Node<E> tmp=head;
while(tmp.next!=null){
tmp=tmp.next; //当tmp结点为最后一个节点的时候
}
tmp.next=node; //将node结点添加到tmp结点后面
}
/*删除链表中的第index个值*/
public void deleteData(int index){
Node<E>pre=head;
Node<E>post=head;
while(pos!=index){
pre=post;
post=post.next;
pos++;
}
pre.next=post.next;//pre结点的指针直接指向post的下一个指针 跳过post将其删除
pos=0;
}
/*根据index查找结点信息*/
public Node<E> findNodebyIndex(int index){
Node<E>current=head;
while(pos!=index){
current=current.next;
pos++;
}
return current;
}
/*显示所有的结点信息*/
public void displayAllNodes(){
Node<E>current=head;
while(current!=null){
current.display();
current=current.next;
}
System.out.println();
}
public static void main(String[] args){
LearnLink<Integer> link=new LearnLink<>();
link.addFirstNode(22);
link.addDatatoLink(25);
link.addItemtoIndex(2,23);
link.addItemtoIndex(3,24);
link.addItemtoIndex(4,25);
link.deleteData(3);
link.displayAllNodes();
Node node1 = link.findNodebyIndex(1);
System. out.println( "node1: " + node1. data);
/*
* 输出:
* 22 25 23 25 //本来是22 25 23 24 25 删除了24
node1: 25
*/
}
}