链表的java实现和常用操作实现方法

本文介绍了一个简单的Java链表实现,包括节点的增加、删除等基本操作,并提供了完整的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.用java实现链表结构,有增加、删除方法

注意,链表要有head;

public class MyList {
	//头结点
	Node head = null;
	
	class Node {
		int data;
		Node next = null;
		public Node(int data) {
			this.data = data;
		}
	}
	/**
	 * 链表尾部插入节点
	 */
	public void add(int d) {
		Node node = new Node(d);
		if(head==null) {
			head = node;
			return;
		}
		Node tmp = head;
		while(tmp.next != null) {
			tmp = tmp.next;
		}
		tmp.next = node;
	}
	/**
	 * 链表删除第index节点(从1开始)
	 */
	public boolean delete(int index) {
		if(index<1 || index > length()) {
			return false;
		}
		if(index == 1) {
			head = head.next;
			return true;
		}
		int i=1;
		Node pre = head;
		Node cur = head.next;
		while(cur!=null) {
			if(i == index) {
				pre.next = cur.next;
				return true;
			}
			pre = cur;
			cur = cur.next;
			i++;
		}
		return false;
	}
	/**
	 * 返回节点长度
	 */
	private int length() {
		int length = 0;
		Node tmp = head;
		while(tmp.next != null) {
			length ++;
			tmp = tmp.next;
		}
		return length;
	}
	/**
	 * 在不知道头指针的情况下删除指定节点,该节点为尾节点时返回false【有点问题!】
	 */
	public boolean delete(Node n) {
		Node node = null;
		if(n.next != null) {
			node = n.next;
			node.data = n.next.data;
			n = node;
			n.data = node.data;
			return true;
		} else {
			n = null;
			return false;
		}
	}
}

2.链表常用操作

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值