首页 > 技术文章 > Java单链表的实现

aituming 2015-08-29 16:40 原文

将结点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"));

	}

}

  

推荐阅读