JAVA实现单链表的增删改查
思路实现
定义 head=null,tali=null
head是头节点,tail是尾节点。
代码实现
public class Chain {
/**
*
* @author 远航小陈家
* Node:定义node的结构
*
*/
class Node {
public int data;
public Node next;
}
/**
* 定义头节点和尾节点
* 尾节点永远指向最后一个元素
*/
private Node head=null;
private Node tail=null;
/**
*
* 向链表中添加元素
* @param data :类型int类型
* @return :插入成功返回ture
*/
public boolean add(int data) {
if(head==null) {
Node headNode=new Node();
headNode.data=data;
head=headNode;
tail=headNode;
return true;
}
else {
Node node=new Node();
node.data=data;
tail.next=node;
tail=node;
return true;
}
}
/**
* 更改链表中的所有元素
* @param data:原链表中的元素
* @param target:修改后的值
* @return:修改成功返回true,失败返回false
*/
public boolean update(int data,int target) {
Node node =new Node();
node.data=data;
Node temp=head;
while(temp!=null) {
if(temp.data==data) {
temp.data=target;
return true;
}
else {
temp=temp.next;
}
}
return false;
}
/**
*
* 删除链表中的元素
* @param data
* @return:删除成功返回true,失败返回false;
*/
public boolean del(int data) {
Node node=new Node();
node.data=data;
if(head.data==node.data) {
head=head.next;
return true;
}
else {
Node pre=head;//记录删除节点的前驱节点
Node target=head.next;
while(target!=null) {
if(target.data==node.data) {
pre.next=target.next;
return true;
}
else {
pre=pre.next;
target=target.next;
}
}
}
return false;
}
/**
* 遍历链表的所有元素
*/
public void printNode() {
while(head!=null) {
int data=head.data;
head=head.next;
System.out.println(data);
}
}
}
在main方法中测试
public class Main {
public static void main(String[] args) {
Chain chain=new Chain();
chain.add(1);
chain.add(2);
chain.add(3);
chain.add(4);
chain.add(5);
chain.update(5, 0);
chain.del(5);
chain.printNode();
}
}