简单单向链表
[java] view
plaincopyprint?
- class Node{
- private String data; //存储当前节点内容
- private Node next=null; //存储下一下节点
- public Node(String data){
- this.setDate(data);
- }
- public void setDate(String data){
- this.data = data;
- }
- public void setNext(Node next){
- this.next = next;
- }
- public String getDate(){
- return this.data;
- }
- public Node getNext(){
- return this.next;
- }
- }
- public class LinkDemo01
- {
- public static void main(String args[]){
- Node n1 = new Node("节点-A");
- Node n2 = new Node("节点-B");
- Node n3 = new Node("节点-C");
- Node n4 = new Node("节点-D");
- n1.setNext(n2);
- n2.setNext(n3);
- n3.setNext(n4);
- printNode(n1);
- }
- public static void printNode(Node node){
- System.out.println(node.getDate());
- if(node.getNext()!=null){
- printNode(node.getNext());
- }
- }
- }
单向链表整合内部类
[java] view
plaincopyprint?
- class Link
- {
- class Node
- {
- private String data;
- private Node next=null;
- public Node(String data){
- this.setData(data);
- }
- public void setData(String data){
- this.data = data;
- }
- public void setNext(Node next){
- this.next = next;
- }
- public String getData(){
- return this.data;
- }
- public Node getNext(){
- return this.next;
- }
- public void add(Node node){
- if(this.next==null){
- this.next = node;
- }else{
- this.next.add(node);
- }
- }
- public void print(){
- if(this.next==null){
- System.out.println(this.getData());
- }else{
- System.out.println(this.getData());
- this.next.print();
- }
- }
- public boolean search(String data){//内部搜索方法
- if(data.equals(this.data)){
- return true;
- }else{//向下继续判断
- if(this.next!=null){
- return this.next.search(data);
- }else{
- return false;
- }
- }
- }
- public void delete(Node previous,String data){
- if(data.equals(this.data)){
- previous.next = this.next;//空出当前节点
- }else{
- if(this.next!=null){
- this.next.delete(this,data); //继续查找
- }
- }
- }
- }
- private Node root; //根节点
- public void addNode(String data){
- Node newNode = new Node(data); //创建新节点
- if(this.root==null){
- this.root = newNode;
- }else{
- this.root.add(newNode);
- }
- }
- public void printNode(){
- if(this.root!=null){
- this.root.print();//调用Node类中的输出操作
- }
- }
- public boolean contains(String name){
- return this.root.search(name); //调用Node类的查找方法
- }
- public void deleteNode(String data){
- if(this.contains(data)){ //判断节点是否存在
- if(this.root.getData().equals(data)){
- this.root = this.root.next; //修改根节点
- }else{
- this.root.next.delete(root,data); //把下一个节点的前节点和数据一起传入进去
- }
- }
- }
- }
- public class LinkDemo02
- {
- public static void main(String args[]){
- Link l = new Link();
- l.addNode("节点-A");
- l.addNode("节点-B");
- l.addNode("节点-C");
- l.addNode("节点-D");
- //增加之后的内容
- l.printNode();
- //判断是否包含节点
- System.out.println(l.contains("节点-X"));
- l.deleteNode("节点-B");
- //删除之后的内容
- l.printNode();
- }
- }
总结:
1.类的职能不同,LinkDemo01是基础链表类,而LinkDemo02的内部类为基础链表类,外部类为链表操作类。
2.基础链表类中存在一个this.next指向下一个链表对象。
时间: 2024-10-11 03:21:49