zoukankan      html  css  js  c++  java
  • Java单链表的实现

    将结点Node进行封装,假设Node的操作有增加,删除,查找,打印几个操作。将Node实现为链表Link的内部类,简化代码。

    package Chapter5;
    
    import java.security.cert.LDAPCertStoreParameters;
    
    class Link{
    	class Node{
    		private String data;
    		private Node next;
    		public Node(String data){
    			this.data = data;
    			this.next = null;
    		}
    		
    		public void add(Node newNode) {
    			if(this.next == null){
    				this.next = newNode;
    			}
    			else{
    				this.next.add(newNode);
    			}
    		}
    		
    		public void print(){
    			System.out.print(this.data+"-->");
    			if (this.next!=null) {
    				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 pre, String data){
    			if(data.equals(this.data)){
    				pre.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) {
    			root = newNode;
    		}
    		else{
    			this.root.add(newNode);
    		}
    	}
    	
    	public void printNode() {
    		if (this.root!=null) {
    			this.root.print();
    		}
    		System.out.println();
    	}
    	
    	public boolean contains(String data){
    		return this.root.search(data);
    	}
    	
    	public void deleteNode(String data) {
    		if(contains(data)){
    			if(this.root.data.equals(data))
    				this.root = this.root.next;
    			else{
    				this.root.delete(root, data);
    			}
    		}
    	}
    }
    
    
    public class LinkDemo01 {
    
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
    		Link l = new Link();
    		l.addNode("A");
    		l.addNode("B");
    		l.addNode("C");
    		l.addNode("D");
    		
    		l.printNode();
    		
    		l.deleteNode("B");
    		l.addNode("E");
    		l.printNode();
    		
    		System.out.println(l.contains("A"));
    
    	}
    
    }
    

      

  • 相关阅读:
    垂直水平居中几种实现风格
    重绘(repaint)和回流(reflow)
    对象深拷贝
    PhantomJS not found on PATH
    d3.js 数据操作
    canvas 绘制圆弧
    d3.js 柱状图
    d3.js -- 比例尺 scales scaleLinear scaleBand scaleOrdinal scaleTime scaleQuantize
    d3.js -- select、selectAll
    map映射
  • 原文地址:https://www.cnblogs.com/aituming/p/4769367.html
Copyright © 2011-2022 走看看