728x90
300x250

[자료구조(Data Structure)] - 6. Linked Queue

 

1. Linked Queue 동작 로직

 

a. 삽입(push)

 

b. 인출(pop)

 

 

2. Linked Queue ADT

 

 abstract interface Queue{

       abstract void Push( Object x );

       abstract Object pop();

       abstract boolean isEmpty();

 }

 

 Queue Interface ADT

 

 

 
class LinkedNode{
        private Object data;
        private LinkedNode next;
 
        public void setData(Object x)
        {
             this.data = x;
        }


       public void setNext(LinkedNode node)
       {
             this.next = node;
       }

       public Object getData()
       {
            return this.data;
       }

       public LinkedNode getNext()
       {
            return this.next;
       }
}

LinkedNode ADT

 

3. 코드 구현

 

 

 abstract interface Queue{

       abstract void Push( Object x );

       abstract Object pop();

       abstract boolean isEmpty();

 }

 class LinkedNode{
        private Object data;
        private LinkedNode next;
 
        public void setData(Object x)
        {
             this.data = x;
        }


       public void setNext(LinkedNode node)
       {
             this.next = node;
       }

       public Object getData()
       {
            return this.data;
       }

       public LinkedNode getNext()
       {
            return this.next;
       }
}

 class LinkedQueue implements Queue{

          private LinkedNode front;
          private LinkedNode rear;
 
          public LinkedQueue(){
                 this.front = null;
                 this.rear = null;
          }
 
          public void push(Object x){
  
                 LinkedNode newNode = new LinkedNode();

                 newNode.setData( x );
                 newNode.setNext( null );

              

                 if( isEmpty() )
                 {
                       this.front = newNode;
                       this.rear = newNode;  
                 }
                 else{
                       this.rear.setNext ( newNode );
                       this.rear = newNode;
                 }

          }

 

          public Object pop(){
   
                 if ( isEmpty() )
                       return null;
  
                 Object data = front.getData();
   
                 LinkedNode prevnode = front;
                 front = front.getNext();
 
                 prevnode = null;
                 return data;
         }

 

         public Object peak(){
  
                if ( isEmpty() )
                        return null;
                else
                        return front;

         }

 

         public boolean isEmpty(){
  
                if(front == null)
                        return true;
                else
                        return false;  

          }
 
          public void viewOfAll()
          {
                LinkedNode current = this.front;
  
                System.out.println("출력 ---------");
 
                while ( current != null )
                {
                         System.out.println( current.getData() );
                         current = current.getNext();
                 }

           }

 }

 
public class LinkedQueueProgram{
 
         public static void main(String args[])
         {
                 LinkedQueue queue = new LinkedQueue();
                 queue.push("1번");
                 queue.push("2번");
                 queue.push("3번");
                 queue.viewOfAll();

 

                 queue.pop(); 
                 queue.viewOfAll();
 
                 queue.push("1번");
                 queue.viewOfAll();

         }
}

 LinkedQueueProgram.java

 

 

반응형
728x90
300x250
[자료구조(Data Structure)] - 5. Circular Queue with Array

 

먼저 환형 큐 with 배열을 소개하면, 여러분들 원으로 된 시계 잘 아신가요??

 

1. 잔머리 굴려보기

 

 

실제로는 원이 아닙니다. 배열 index가 마치 회전하는 듯한 연상이 이해하는 데 도움이 되기 때문에 그려 놓은 겁니다.

예를 들어 저기 원이 Size가 4개인데, 회전하는 데 있어서 회전을 균일하게 잡아줄 공간이 필요합니다.

 

저 원이 예를 들어 Size가 4라고 하면, 실제로 사용가능한 공간은 Size 3입니다.

 

잉여공간 1개를 부여하지 않으면, rear index가 기존에 있는 데이터를 하나 잡아 먹게 됩니다.

(이 부분은 여러분들이 한번 아래의 코드를 수정해서 생각해보시기 바랍니다.)

(또는 종이로 한번 그려보시기 바랍니다.)

 

갑자기 설명하는데, 잔 테크닉 먼저 이야기해서 난해하셨을 것 같습니다.

다시 기본 원리에 대해 소개 해드리겠습니다.

 

2. 기본 원리는?

 

먼저 동작 원리를 구현한 결과입니다. (파워포인트로 그리기엔 솔직히 귀찮고 힘든 일입니다.)

대신 코드 동작으로 똑같이 표현해드리겠습니다.

 

먼저 Queue 자료 구조의 ADT형을 이해하기에 앞서 용어를 이해하기 쉽게 설명해드리고 ADT를 설명해드리겠습니다.

push (어떤 책에선 enqueue( datatype x ) ), pop (어떤 책에선 dequeue ( ) )라고 표기합니다.

 

 abstract interface Queue{

      abstract void push ( Object x ) ;

      abstract Object pop ( ) ;

      abstract boolean isEmpty ( );

      abstract Object peak ( ) ;

 }

 Queue의 ADT

 

큐(Singly Queue), 환형 큐(Circular Queue)나, 연결 큐(Linked Queue) 등 기본 ADT는 이걸로 사용합니다.

이건 Stack ADT나 동일합니다. (소개하지 않아서 언급은 여기서 ~ 끝)

 public class ArrayQueue implements Queue{

 

      private int front;

      private int rear;

      private int count;

      private int queuesize;

     

      private Object[] itemArray;

 

      public ArrayQueue()

      {

               this.front = 0;

               this.rear = 0;

               this.count = 0;

               this.queueSize = 10;

               this.itemArray = new Object [ this.queueSize ];

      }

 } 

 배열 큐 - Circular Queue 구현 - 기본 Instance Variable, Constructor


Push(삽입) 원리

 

 rear = ( rear + 1 ) % n

 itemArray[rear] = x ;

 

Pop(인출) 원리

 

 front = ( front + 1 ) % n

 Object data = itemArray ( front );

 

 

3. 코드로 한번 실험해보세요.

 

 
abstract interface Queue{
 
        abstract boolean isEmpty();
        abstract void push(Object x);
        abstract Object pop();
        abstract Object peak(); 
}

 

class ArrayQueue implements Queue{

         private int front;
         private int rear;
         private int count;
         private int queueSize;
         private int increment;
         private Object[] itemArray;
 
         public ArrayQueue( )
         {
                 this.front = 0;
                 this.rear = 0;
                 this.count = 0;
                 this.increment = 5;
                 this.queueSize = 5;

                 itemArray = new Object[queueSize];
          }

 

          private void queueFull()
          {
  
                 int prevQueueSize = queueSize;
                 queueSize += increment ;
  
                 Object[] prevItemArr = itemArray.clone();
                 itemArray = new Object[queueSize];
  
                 int i = 0;

                 while( i < prevQueueSize )
                 {
                         itemArray[i] = prevItemArr[front];
                         front = (front + 1) % prevQueueSize;
   
                         i++;
                 }

 

                 front = 0;
                 rear = count;
        }
 
        public boolean isEmpty(){
                 return (count == 0) ? true : false ;
        }

        public void push(Object x){
  
                 if ( ( count + 1 ) ==  queueSize )
                        queueFull();

 

                 rear = ( rear + 1 ) % queueSize;
                 itemArray[ rear ] = x;
  
                 count++;

        }

 

        public Object pop(){

                if( isEmpty() )
                       return null;
  
                front = (front + 1) % queueSize;
                Object item = itemArray[front];
                itemArray[front] = null;
  
                count--;

                return item;
         }
 
          public Object peak(){
  
               if( isEmpty() )
                       return null;
               else
                       return itemArray[front];

          }

 

           public void viewOfAll( String label )
           {
                   System.out.println ( "\n\n[" + label + "]/-----실험결과" );
    
                   for ( Object x : itemArray )
                  {
                            System.out.println ( x );   

                   }

            }

 

             public int getCount()
             {
                     return this.count;
             }
 }

 

 public class QueueProgram{

             public static void main(String args[])
             { 

                     ArrayQueue queue = new ArrayQueue();
  
                     queue.push("1번");
                     queue.push("2번");
                     queue.push("3번");
                     queue.push("4번");
                     queue.viewOfAll("1번");

 

                     queue.pop();
                     queue.viewOfAll("2번");

 

                     queue.push("5번");
                     queue.viewOfAll("3번");

 

                     queue.push("6번");
                     queue.viewOfAll("4번");

 

                     queue.pop();
                     queue.viewOfAll("5번");


                     queue.pop();
                     queue.viewOfAll("6번");

 

                     queue.push("7번");
                     queue.viewOfAll("7번");

 

                     queue.push("8번");
                     queue.viewOfAll("8번");

 

                     queue.pop();
                     queue.viewOfAll("9번");

 

                     queue.pop();
                     queue.viewOfAll("11번");

 

                     queue.push("9번");
                     queue.viewOfAll("12번");

 

                     queue.push("10번");
                     queue.viewOfAll("13번");

 

                     queue.push("11번");
                     queue.viewOfAll("14번");

 

                     queue.push("12번");
                     queue.viewOfAll("15번");
 
         }

}

 QueueProgram.java

 

반응형
728x90
300x250

[자료구조(Data Structure)] - 2. Insertion Sort

 

[슈도코드]
 

void insertsort(int *arr, int n)

{

int i = 1;

int j ;

int temp ;

 

while ( i < n )

{

temp = arr[i] ;

j = i - 1;

 

while ( j >= 0 && ( temp < pArr[ j ] ) )

{

pArr [ j + 1 ] = pArr[ j ] ;

j-- ;

}

pArr [ j + 1 ] = temp ;

 

}

}

 

 

반응형
728x90
300x250

[자료구조(Data Structure)] - Partition 기법 - QuickSort

 

Quick Sort의 Patition 방법에 대한 것이다.


1. 추천의 글

 

 

그림1-1) Partitioning Strategy, s4_Quick_soft.pdf

 

글을 읽어보면 가장 잘 나왔다고 생각되는 점이 분할 전략이다.

 

[첨부(Attachment)]

s4_quick_sort.pdf 

 


2. 참고자료(Reference)

 

1. http://www.eecs.yorku.ca/course_archive/2010-11/W/2011/Notes/s4_quick_sort.pdf, Accessed by 2014. 10. 19

 

 

반응형
728x90
300x250
[C언어] 포인터 개념의 이해

(별 ****) 어셈블리어 수준에서의 고속 연산과 빠른 처리 성능을 내기 위해서는 무엇보다 메모리에 대한 직접 접근이 필요합니다.
C언어는 데이터가 적재된 메모리 주소를 직접 참조하기 위한 방법으로 포인터(Pointer)를 지원해야합니다. 즉 특정 변수에 정수나 실수, 문자 상수뿐만 아니라 물리적인 메모리 번지도 담아두고 활용할 수 있다는 뜻이기도 하지요.
아래에 포인터의 표준 형식입니다.

data_type * variable_name;

data_type 에는 다음과 같은 종류의 범위가 적용이 됩니다.

int, char, unsigned char, short, short int 등과 같이 일상적으로 사용하는 대부분의 변수들을 사용하실 수가 있습니다.

포인터를 쉽게 이해하실려면 메모리주소를 이해하셔야 합니다.

예) 개똥이네 집주소 1111가 있습니다. 철수와 영희네 집주소는 각각 1112, 1113입니다. 철수네는 CP라는 자료를 가지고 있습니다. 개똥이는 철수네 집의 주소를 사용하고자 합니다. 그래서 *라는 아이를 붙여진 영역을 갖게 되었죠. 여기에서 *라는 녀석은 주소번호를 뜻합니다.
우체국에 가서 '아저씨, 철수네 집이 여행을 가서 그러는데 개똥이네 집에 데이터를 같이써도 되나요'라고 문의를 해서 좋다라고 허락하셨습니다. &라는 주소연산자를 통해 아래와 같이 사용하게 되었습니다.

int *1111, 1112, 1113

1112 = CP;
1113 = 0;

1111 = &1112;

그래서 포인터라는 아이로 철수네는 철수네로 개똥이네는 철수네 데이터를 불러오는 게 성립이 되었습니다.(믿거나 말거나....)

Q1. 실제로 포인터가 대부분의 C 응용프로그램을 제작할 때 필수적으로 쓰인다는데, 과연 어디에 사용이 될까요??

첫번째
I.O라고 불리우는 입축력 하드웨어 장치 드라이버를 만드는 경우를 예를 들어보자면 송수신의 대부분이 메모리를 통해 일어나게 되죠?
흔히 이를 memory-mapped I/O라고 합니다. 이 경우에는 효율적인 메모리 관리가 요하기에 사용히 필수라고 할수 있겠죠...

두번째
수시로 발생하는 많은 양의 데이터를 효과적으로 관리해야 할 프로그램에서는 프로그램이 실행되는 도중(run-time)에 필요한 메모리를 동적으로 할당받아 연결리스트(linked-list) 자료구조를 구성해야 하는 경우가 있다. 이 경우에도 포인터를 사용해야만 보다 빠른 자료의 검색이 가능하고 우수한 성능을 낼 수 있다.

마지막으로...
여러분이 좋아하는 게임을 만드는 경우를 생각해보자...
이 경우에도 게임에 사용되는 각종 배경 이미지와 에니메이션 데이터를 비디오 메모리 공간에 미리 로딩해 두고, 포인터로 직접 접근해야만 끊어짐 없는 부드러운 에니메이션을 표현할 수가 있습니다.

[Note]
자바와 같은 대부분의 프로그래밍 언어는 포인터를 직접적으로 지원하지 않습니다. 즉, 프로그램의 안정성을 위해 개발자가 메모리 주소를 직접 제어하는 것을 막고 있습니다.
반응형

'소프트웨어(SW) > GNU - C, C++' 카테고리의 다른 글

[C언어] 포인터 연산  (0) 2009.05.13
[C언어] 포인터에 익숙해지는 방법은...  (0) 2009.05.13
[GNU - C, C++] Dev C++ 5.0 - IDE  (0) 2009.03.30
연산자와 C언어  (0) 2009.03.30
C언어 입문의 시작  (0) 2009.03.20

+ Recent posts