자바 를 사용 하여 양 방향 링크 데이터 구 조 를 실현 합 니 다.

오늘 xxxx 회사 에 면접 을 보 러 갑 니 다. 앞의 일부 문 제 는 모두 인터넷 의 일부 면접 문제 입 니 다. 마지막 문 제 는 데이터 구 조 를 고찰 하여 대학 에서 배 운 데이터 구 조 를 소개 하고 코드 로 링크 의 증가, 삭제, 조 회 를 실현 합 니 다.그 전에 연습 을 할 때 링크 의 Demo 를 썼 는데 이 중요 한 순간 에 잊 어 버 렸 습 니 다. 어떻게 써 야 할 지 모 르 겠 습 니 다. 돌아 와 서 전에 쓴 코드 를 펼 쳐 서 다시 한 번 보 았 습 니 다. 여기 서 제 가 전에 쓴 코드 를 붙 여서 여러분 들 이 공부 할 수 있 도록 하 겠 습 니 다. 여러분 들 이 얻 을 수 있 기 를 바 랍 니 다.
package link;

public class Link {
	
	/**
	 *        ,               
	 * @author binchen
	 *
	 */
	class Node{
		private String data;
		private Node next; //       
		
		public Node(){}
		public Node(String data){
			this.data = data; //            
		}
		public String getData() {
			return data;
		}
		public void setData(String data) {
			this.data = data;
		}
		public Node getNext() {
			return next;
		}
		public void setNext(Node next) {
			this.next = next;
		}
		
		/**
		 *       
		 */
		public void print(){
			System.out.println(this.data + "\t");
			if(this.next != null){
				this.next.print();
			}
		}
		
		/**
		 * 	      
		 * @param newNode
		 */
		public void add(Node newNode){ //           
			if(this.next == null){
				this.next = newNode;
			}else{ //     ,        next
				this.next.add(newNode);
			}
	 	}
		
		/**
		 *     
		 * @param data
		 * @return
		 */
		public boolean search(String data){ //       
			if(this.data.equals(data)){
				return true;
			}else{ //      
				if(this.next != null){ //     null,         
					return this.next.search(data);
				}
				return false;
			}
		}
		
		/**
		 *     
		 * @param data
		 */
		public void deleteNode(Node previous , String name){
			if(name.equals(this.data)){
				previous.next = this.next;
			}else{
				if(this.next != null){
					this.next.deleteNode(this, name);
				}
			}
		}
	};
	
	
	
	private Node root; //            
	public void setRoot(Node root){
		this.root = root;
	}
	public Node getRoot(){
		return this.root;
	}
	
	/**
	 *       
	 * @param data
	 */
	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(); //           
		}
	}
	
	/**
	 *     
	 * @param name
	 * @return
	 */
	public boolean contains(String name){
		return this.root.search(name); //  node       
	}
	
	/**
	 *     
	 * @param name
	 */
	public void deleteNode(String data){
		if(this.contains(data)){ //        
			//                   
			if(this.root.data.equals(data)){ //      
				this.root = this.root.next;  //     ,            
			}else{
				this.root.next.deleteNode(root,data);
			}
		}
	}
}

좋은 웹페이지 즐겨찾기