Java面向对象基础--实现单向链表
2013-09-22 14:44
537 查看
1、设计节点类
以string为数据保存内容,还必须有一个属性保存下一个节点的引用地址。class Node{ // 定义节点类 private String data ; // 保存节点内容 private Node next ; // 表示保存下一个节点 public Node(String data){ // 通过构造设置节点内容 this.data = data ; // 设置内容 } public void setNext(Node next){ this.next = next ; // 设置下一个节点 } public Node getNext(){ // 取得下一个节点 return this.next ; } public String getData(){ return this.data ; // 取得节点的内容 } };
2、测试节点类
class Node{ // 定义节点类 private String data ; // 保存节点内容 private Node next ; // 表示保存下一个节点 public Node(String data){ // 通过构造设置节点内容 this.data = data ; // 设置内容 } public void setNext(Node next){ this.next = next ; // 设置下一个节点 } public Node getNext(){ // 取得下一个节点 return this.next ; } public String getData(){ return this.data ; // 取得节点的内容 } };
public class LinkDemo01{
public static void main(String args[]){
Node root = new Node("火车头") ; // 定义根节点
Node n1 = new Node("车厢-A") ; // 定义第一个车厢(第一个节点)
Node n2 = new Node("车厢-B") ; // 定义第二个车厢(第二个节点)
Node n3 = new Node("车厢-C") ; // 定义第三个车厢(第三个节点)
root.setNext(n1) ; // 设置火车头的下一个节点是第一个车厢A
n1.setNext(n2) ; // 设置第一个车厢的下一个节点是第二个车厢
n2.setNext(n3) ; // 设置第二个车厢的下一个节点是第三个车厢
n3.setNext(null);
printNode(root) ; // 从头开始输出
}
//递归操作,进行输出
public static void printNode(Node node){ // 输出节点
System.out.print(node.getData() + "\t") ; // 输出节点的内容
if(node.getNext()!=null){ // 判断此节点是否存在下一个节点
printNode(node.getNext()) ; // 向下继续输出
}
}
};
相关文章推荐
- 巩固JAVA面向对象基础应用 -- 实现小巧的数据库1
- Java面向对象基础--链表的改进
- JAVA随笔 一 Java面向对象基础和String
- java基础教程:面向对象之抽象类(16)
- JAVA基础训练——用链表实现队列
- Java面向对象基础
- Java基础_面向对象_求指定项 的菲(斐)波那契数列 值
- 黑马程序员 java 基础 毕向东 面向对象 集合框架 List Set
- java基础系列之三:java的面向对象程序设计
- 黑马程序员.Android攻城狮.JAVA基础.1.3.Java面向对象
- Java 面向对象基础 以及进阶知识 总结
- Java面向对象基础知识点
- Java 实现单向链表
- 黑马程序员--Java基础--面向对象之三大特性
- java基础十二 面向对象特点_继承
- java面向对象基础
- JAVA基础学习--面向对象试题
- Java基础—— 面向对象基础
- 数据结构Java实现【3】----单向链表的插入和删除
- 黑马程序员——Java基础---面向对象总结