Java面向对象_数据结构之链表
2024-08-29 15:34:28
链表:是一种常见的基础数据结构,是一种线性表,但是并不会按线性的顺序存储数据,而是在每一个节点里村到下一个节点的指针。
在链表数据结构中,需要使用到递归算法。递归算法是一种直接或间接地调用自身算法的过程。
public class Practice14 { public static void main(String[] args) {
// TODO Auto-generated method stub
jiecheng(5);
System.out.println(jiecheng2(5));
}
//递归写法(很简单)
//注意递归必须要有出口,递归过多会造成内存栈溢出
public static int jiecheng2(int num){
if(num==1)return 1;
return num*jiecheng2(num-1);
}
//求阶乘(普通写法)
public static void jiecheng(int num){ int sum=num;
int i=num-1;
do{
sum=sum*i;
i--;
}while(i>1);
System.out.println(sum);
} }
链表数据结构用于适合频繁进行添加、插入、删除操作,举个例子:
//链表数据结构用于适合频繁进行添加、插入、删除操作
public class Practice14 { public static void main(String[] args) {
// TODO Auto-generated method stub
NodeManager nm=new NodeManager();
nm.addNode("1");
nm.addNode("2");
nm.addNode("3");
nm.addNode("4");
nm.printNode();
nm.delNode("3");
nm.printNode();
} }
//节点管理类
class NodeManager{
private Node root;//根节点
public void addNode(String name){
if(root==null){
root=new Node(name);
}else{
root.add(name);
}
} public void delNode(String name){
if(root.getName().equals(name)){
root=root.next;
}else{
root.del(name);
} } public void printNode(){
if(root!=null){
System.out.print(root.getName()+"->");
root.print();
System.out.println();
} }
//每个节点对象
class Node{
private String name;
private Node next;//表示当前节点的下一个节点
public Node(String name){
this.name=name;
} public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
//添加节点
public void add(String name){
if(this.next==null){
this.next=new Node(name);
}else{
this.next.add(name); //递归
}
}
//删除节点
public void del(String name){
if(this.next!=null){
if(this.next.name.equals(name)){
this.next=this.next.next;
}else{
this.next.del(name);
}
}
}
//输出节点
public void print(){
if(this.next!=null){
System.out.print(this.next.getName()+"->");
this.next.print();
}
}
}
}
最新文章
- 百度地图坐标纠偏和转换工具和DLL
- 在VS项目中通过GIT生成版本号作为编译版本号
- 3.3html学习笔记之链接
- 跨平台的游戏客户端Socket封装,调整
- [置顶] Android访问控制系统测试与评估
- delphi webbrowser 经常使用的演示样本
- XTEA加密算法
- JavaScript系统学习小结——变量、作用域和内存问题
- HTML 基本语法速查
- php opcodes运行原理
- ant 相关命令
- 四大中三家已面向客户推出机器人业务解决方案?别逗了,先用机器人自我革命吧! post by 上海嘉冰信息技术
- MySQL主主同步配置
- cad.net的undo返回操作
- 用canvas画弧形进度条
- Set keys=Map.keyset()
- google play apk 下载
- Codeforces Round #360 (Div. 2) A. Opponents 水题
- RDO部署多节点OpenStack Havana(OVS+GRE)
- [sqlserver脚本]查看指定SQL语句生成了哪些执行计划