JAVA学习之LinkedList

本文介绍了一种基础数据结构——链表,并通过Java代码实现了链表的基本操作:添加、删除、更新及打印节点。通过递归的方式实现了链表的增删改查等功能。
链表(Linked list)一种常见的基础数据结构,是一种线性表,但是并不会按线性的顺序存储数据,而是在每一个节
点里存到是下一个节点的指针(Pointer)。

以下代码实现了一个基础链表的增删改查。
package com.jd.digui;

public class LinkedList {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		NodeManager nm=new NodeManager();
		nm.add(1);
		nm.add(2);
		nm.add(3);
		nm.add(4);
		nm.add(5);

		nm.print();

		nm.del(4);
		nm.print();

		nm.update(2, 7);
		nm.print();
	}

}

class NodeManager{
	private Node root;//根节点
	//空的构造方法
	public NodeManager() {
		super();
	}
	//带参数的构造方法,参数为NoteManager类的内部类
	public NodeManager(Node root) {
		super();
		this.root = root;
	}
	/**
	 * @param date 要添加的数据
	 * 提供给外部调用的添加节点
	 */
	public void add(int date){
		if(root!=null){//如果根节点,也就是第一个节点不为空,就调用Note节点的添加方法
			root.addNode(date);
		}else{
			root=new Node(date);//要是为空,就先实例化Note节点
		}
	}
	/**
	 * @param date 要删除的数据
	 * 提供给外部调用的删除节点
	 */
	public void del(int date){
		if(root.getDate()==date){
			root=root.next;
		}else{
			root.delNode(date);
		}
	}

	/**
	 * @param oldNote 要修改的数
	 * @param newNote 修改后的数
	 */
	public int update(int oldNote,int newNote){
		if(root.getDate()==oldNote){
			root.date=newNote;
		}else{
			root.updateNote(oldNote,newNote);
		}
		return newNote;
	}
	/**
	 * 提供给外部调用的输出节点
	 */
	public void print(){
		if(root!=null){
			System.out.print(root.getDate()+"-->");
			root.printNote();
			System.out.println();
		}
	}

	private class Node{
		private int date;//存储的数据
		private Node next;//这句代表可以一直存储数据,没有长度限制

		public Node(int date) {
			super();
			this.date = date;
		}



		public int getDate() {
			return date;
		}







		/**
		 * @param date
		 * 添加节点
		 */
		public void addNode(int date){
			if(this.next==null){
				this.next=new Node(date);
			}else{
				this.next.addNode(date);
			}
		}
		/**
		 * @param date
		 * 删除节点
		 */
		public void delNode(int date){
			if(this.next!=null){
				if(this.next.date==date){
					this.next=this.next.next;
				}else{
					this.next.delNode(date);
				}
			}
		}

		/**
		 * @param oldNote 要修改的数
		 * @param newNote 修改后的数
		 * @return
		 */
		public int updateNote(int oldNote,int newNote){
			if(this.next!=null){
				if(this.next.date==oldNote){
					this.next.date=newNote;
					
				}else{
					this.next.updateNote(oldNote, newNote);
				}
			}
			return newNote;
		}
		/**
		 * @param date
		 * 输出所有节点
		 */
		public void printNote(){
			if(this.next!=null){
				System.out.print(this.next.date+"-->");
				this.next.printNote();
				System.out.println();
			}
		}
	}
}



评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值