체인 테이블의 Java 언어 설명

1982 단어
class Node{// 
	private int m_Data;
	private Node m_Next;
	
	Node(int data){
		m_Data=data;
		m_Next=null;
	}
	Node(int data,Node next){
		m_Data=data;
		m_Next=null;
	}
	void setData(int data){
		m_Data=data;
	}
	int getData(){
		return m_Data;
	}
	void setNext(Node next){
		m_Next=next;
	}
	Node getNext(){
		return m_Next;
	}
}

class LinkList{// 
	Node m_FirstNode;
	
	LinkList(){
		m_FirstNode=null;
	}
	LinkList(int data){
		m_FirstNode=new Node(data);
	}
	String visitAllNode(){
		Node next=m_FirstNode;
		String s="";
		while(next!=null){
			s=s+next.getData()+"; ";
			next=next.getNext();
		}
		return s;
	}
	void insertAtBegin(int data){
		if(m_FirstNode==null)
			m_FirstNode=new Node(data);
		else 
			m_FirstNode=new Node(data,m_FirstNode);
	}
	void insertAfterId(int data,int id){
		Node next=m_FirstNode;
		if(next==null)
			m_FirstNode=new Node(data);
		else{
			while(next.getNext()!=null && next.getData()!=id)
				next=next.getNext();
			next.setNext(new Node(data,next.getNext()));
		}
	}
	boolean removeAtId(int id){
		Node ahead=m_FirstNode;
		Node follow=ahead;
		
		if(ahead==null)
			return false;
		else if(ahead.getData()==id){
			m_FirstNode=m_FirstNode.getNext();
			return true;
		}
		else{
			ahead=ahead.getNext();
			while(ahead!=null){
				if(ahead.getData()==id){
					follow.setNext(ahead.getNext());
					return true;
				}
				follow=ahead;
				ahead=ahead.getNext();
			}
			return false;
		}
	}
	void  removeAll(){
		m_FirstNode=null;
	}
}

public class UseLinkList {// 
	public static void main(String[] args){
		LinkList list=new LinkList(-1);
		
		for(int i=0;i<10;i++){
			list.insertAtBegin(i);
			System.out.println(list.visitAllNode());
		}
		list.insertAfterId(10, 20);
		System.out.println(list.visitAllNode());
		if(list.removeAtId(-1))
			System.out.println(list.visitAllNode());
		else
			System.out.println("no data in linklist");
		list.removeAll();
	}
}

좋은 웹페이지 즐겨찾기