java实现单链表的基本操作

java实现单链表的基本操作

单链表结点的类实现

package com.work.link;
/**
 * 链表结点的实体类
 * @author qingw
 *
 */
public class Node {
	int data; //结点数据
	Node next = null; //指针域,即下一个结点
	
	public Node (int data){
		this.data = data;
	}
}

单链表的各种基本操作java代码实现

package com.work.link;
/**
 * 单链表的一些基本操作
 * @author qingw
 *
 */
public class MyLink {

	Node head = null; //头结点
	/**
	 * 向链表尾插入结点	
	 * @param d
	 */
	public void addNode(int data){
		Node newNode = new Node(data); //实例化一个结点
		if(head==null){
			head = newNode;
		}
		
		Node tmp = head;
		while(tmp.next!=null){
			tmp = tmp.next;
		}
		
		tmp.next = newNode;
	}
	/**
	 * 通过指定的下标index删除链表结点
	 * @param index
	 * @return
	 */
	public boolean deleteNode(int index){
		
		if(index < 1 || index > length()){
			return false;
		}
		
		if(index == 1){
			head = head.next; //删除第一个结点,即头结点,把头结点变成原来头结点的下一个结点就行了
			return true;
		}
		
		int i = 2;
		Node preNode = head;
		Node cruNode = preNode.next;
		while(cruNode != null){
			if(i == index){
				preNode.next = cruNode.next; //删除当前节点,即将前一个结点的下一个结点连接到当前结点的下一个结点就行
				return true;
			}
			preNode = cruNode;
			cruNode = cruNode.next;
			i++;
		}
		
		return false; //如果上面过程中没有返回true,那就说明没有删除成功。
	}
	/**
	 * 根据下标进行查找
	 * @param index
	 * @return
	 */
	public Node searchNode(int index){
		Node cruNode = head;
		int i = 1;
		while(i<=length()){
			if(i == index){
				return cruNode;
			}
			i++;
			cruNode = cruNode.next;
		}
		return null;
	}
	/**
	 * 将新元素data插入到第index个结点之后
	 * @param index
	 * @param data
	 * @return
	 */
	public boolean insert(int index, int data){
		/**插入空表或非空表的第一个结点之前*/
		if(head == null || index == 0){
			Node newNode = new Node(data);
			newNode.next = head;
			head = newNode;
		}else{
			Node cruNode = head;
			for(int k = 1;k < index; k++){
				if(cruNode == null){
					break;
				}else{
					cruNode = cruNode.next;
				}
			}
			if(cruNode == null){
				return false;
			}else{
				Node newNode = new Node(data);
				newNode.next = cruNode.next;
				cruNode.next = newNode;
			}
		}
		return true;
	}
	/**
	 * 返回节点的长度
	 * @return
	 */
	public int length(){
		int length = 0;
		Node tmp = head;
		while(tmp != null){
			length++;
			tmp = tmp.next;
		}
		return length;
	}
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值