JAVA实现单链表的增删改查

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();
	}


}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值