2014년 4월 2일 수요일

[구로JAVA]자바 원형연결리스트(별도의시작노드있는것)-Circular Linked List, [자바개발자교육/자바교육/자바강좌/자바교육잘하는곳/자바교육추천/자바실무교육/JAVA/JAVA교육/JAVA학원/JAVA실무교육]

[구로JAVA]자바 원형연결리스트(별도의시작노드있는것)-Circular Linked List, [자바개발자교육/자바교육/자바강좌/자바교육잘하는곳/자바교육추천/자바실무교육/JAVA/JAVA교육/JAVA학원/JAVA실무교육]
 
//CircularLinkedList Example
//시작노드를 가리키는 별도의 빈headerNode를 둠,,,
class CircularListNode {
    Object data;
    CircularListNode next;   
}
public class CircularList {
    private CircularListNode headerNode;

 public CircularList() {
  headerNode = new CircularListNode();
        headerNode.next = headerNode;
 }
    public synchronized void insert(Object data) {
        CircularListNode tn = new CircularListNode();
        tn.data = data;
  //맨처음 insert되는 경우
  if (headerNode.next == headerNode) {
            tn.next = headerNode;
            headerNode.next = tn;
        } else {                         
      //마지막 노드를 찾는다.(headerNode 이전의 노드)
   CircularListNode p = findPrev(data);
            tn.next = headerNode;
            p.next = tn;
        }
    }
    public synchronized void delete(Object data) {
        CircularListNode prev = findPrev(data);
  CircularListNode p = prev.next;
        if (prev.data.toString().equals(p.data.toString()) && p.next == headerNode) { 
   headerNode.next = headerNode;
   headerNode.data = null;
    return;
  }
  prev.next = p.next; 
    }
 private CircularListNode findPrev(Object data) {
  headerNode.data = data;
        CircularListNode p = headerNode.next;
        do {
   if (p.next.data.toString().equals(data.toString())) return p;
            p = p.next;
        } while (p != headerNode); 
        throw new IllegalArgumentException();
    }
      
 public String toString() {
  StringBuffer sb = new StringBuffer("[");
  CircularListNode p = headerNode.next;
  if (p != null) {
     do {
    if (p.data == null) sb.append(" ");
    else sb.append(" " + p.data.toString());
    p = p.next;   
    if (p != headerNode) sb.append(",");
     } while (p != headerNode);
  }
  sb.append(" ]");
  return sb.toString();
 }
}
 
 
 
class Main {
    public static void main(String[] args) {
  CircularList names = new CircularList();
  names.insert(new String("Scott"));
  names.insert(new String("Tiger"));
  names.insert(new String("Swan"));   
  System.out.println(names);
  // Delete item
  names.delete(new String("Swan"));
  System.out.println(names);  
     names.delete(new String("Tiger"));
  System.out.println(names);
  names.delete(new String("Scott"));
  System.out.println(names);
 }
}
 

댓글 없음:

댓글 쓰기