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