现在的位置: 首页 > 综合 > 正文

java 增加 删除 查找 链表。

2018年09月14日 ⁄ 综合 ⁄ 共 1618字 ⁄ 字号 评论关闭
View Code

 1 class Link{
2 class Node{//内部类
3 private String data;
4 private Node next;
5 public Node(String data){//构造方法
6 this.data=data;
7 }
8 public void add(Node newNode){
9 if(this.data==null){
10 this.next=newNode;
11 }else{
12 this.next.add(newNode);
13 }
14
15 }
16 public void print(){//打印
17 System.out.print(this.data+"\t");
18 if(this.next==null){
19 this.next.print();
20 }
21 }
22 public boolean search(String data){//内部定义搜索方法
23 if(data.equals(this.data)){
24 return true;
25 }else{
26 if(this.next!=null){
27 return this.next.search(data);
28 }else{
29 return false;
30 }
31 }
32 }
33 public void delete(Node previous,String data){
34 if(data.equals(this.data)){
35 previous.next=this.next;
36 }else{
37 if(this.next!=null){
38 this.next.delete(this,data);
39 }
40 }
41 }
42 };
43 private Node root;
44 public void addNode(String data){
45 Node newNode=new Node(data);
46 if(this.root==null)
47 {this.root=newNode;}
48 else
49 this.root.add(newNode);
50
51 }
52 public void printNode(){
53 if(this.root!=null){
54 this.root.print();
55 }
56 }
57 public boolean contains(String name){//判断元素是否存在
58 return this.root.search(name);
59 }
60 public void deleteNode(String data){
61 if(this.contains(data)){
62 if(this.root.data.equals(data))
63 {this.root=this.root.next;
64 }else{
65 this.root.next.delete(root,data);
66 }
67 }
68 }
69 };
70 public class Hello {
71 public static void main(String args[]){
72 Link l=new Link();
73 l.addNode("A");
74 l.addNode("B");
75 l.addNode("C");
76 l.addNode("D");
77 l.addNode("E");
78 System.out.println("==========删除之前==========");
79 l.printNode();
80 l.deleteNode("C");
81 l.deleteNode("D");
82 System.out.println();
83 System.out.println("==========删除之前==========");
84 l.printNode();
85 System.out.println();
86 System.out.println("查询结点:"+l.contains("A"));
87 }
88 }

java  增加,删除,查找 链表。操作

抱歉!评论已关闭.