2012-03-21 7 views
2

프로그래밍 클래스 용으로 연결된 목록 프로그램을 만들어야했습니다. 그것은 작동하고 숫자가 삽입 될 때마다 그것은 목록의 시작 부분에 놓입니다. 이제 선생님은 Linked List 프로그램을 사용하여 숫자를 오름차순으로 정렬하길 원합니다. 나는 이것을하는 방법에 완전히 망한다. 누구든지 올바른 방향으로 나를 가리킬 수 있습니까?Java에서 이중 연결된 목록 정렬

public class SortedList { 

private DoubleNode head = null; 
private int listLength; 

public static void main(String[] args) { 
    SortedList list = new SortedList(); 
    list.insert(6); 
    list.insert(7); 

    System.out.println(list.toString()); 

} 

public void insert(double value) { 

    head = new DoubleNode(value, head); 
    listLength++; 

} 

public String toString() { 

    String answer = "[ "; 
    for (DoubleNode current = head; current != null; current = current 
      .getLink()) { 
     answer += current.getData() + " "; 
    } 
    answer += "]"; 
    return answer; 
} 

public int find(double value) { 
    if (listLength == 0) 
     return -1; 

    int pos = 1; 
    for (DoubleNode current = head; current != null; current = current.getLink()) { 
     if (current.getData() == value) 
      return pos; 
     pos++; 
    } 
    return -1; 
} 

public int size() { 
    return listLength; 
} 

public boolean removeAt(int index) { 
    if (index < 1 || index > listLength) 
     return false; 

    if (index == 1) { 
     if (head != null) { 
      head = head.getLink(); 
      listLength--; 
     } 
     return true; 
    } 

    DoubleNode current = head; 
    for (int i = 1; i < (index - 1); i++) { 
     if (current.getLink() == null) 
      return false; 
     current = current.getLink(); 
    } 
    current.setLink(current.getLink().getLink()); 
    listLength--; 
    return true; 
} 

}

여기 내 교사에 의해 주어진 노드 내 코드입니다 :

// File: DoubleNode.java based on the DoubleNode class by Michael Main 

/************************************************************************** 
* DoubleNode provides a node for a linked list with double data in each node. 
* 
* @note 
* Lists of nodes can be made of any length, limited only by the amount of 
* free memory in the heap. 
* 
* @author Michael Main 
* shortened by Beth Katz and Stephanie Elzer to be only the basics 
* 
* @version 
* February 2007 
***************************************************************************/ 
public class DoubleNode 
{ 
// Invariant of the DoubleNode class: 
// 1. The node's double data is in the instance variable data. 
// 2. For the final node of a list, the link part is null. 
//  Otherwise, the link part is a reference to the next node of the list. 
    private double data; 
    private DoubleNode link; 

/** 
* Initialize a node with a specified initial data and link to the next 
* node. Note that the initialLink may be the null reference, which 
* indicates that the new node has nothing after it. 
* @param initialData 
* the initial data of this new node 
* @param initialLink 
* a reference to the node after this new node--this reference may be 
* null to indicate that there is no node after this new node. 
* @postcondition 
* This node contains the specified data and link to the next node. 
**/ 
public DoubleNode(double initialData, DoubleNode initialLink) 
{ 
    data = initialData; 
    link = initialLink; 
} 

/** 
* Accessor method to get the data from this node. 
* @param - none 
* @return 
* the data from this node 
**/ 
public double getData() 
{ 
    return data; 
} 

/** 
* Accessor method to get a reference to the next node after this node. 
* @param - none 
* @return 
* a reference to the node after this node (or the null reference if 
* there is nothing after this node) 
**/ 
public DoubleNode getLink() 
{ 
    return link;            
} 

/** 
* Modification method to set the data in this node. 
* @param newData 
* the new data to place in this node 
* @postcondition 
* The data of this node has been set to newData. 
**/ 
public void setData(double newData) 
{ 
    data = newData; 
}                

/** 
* Modification method to set the link to the next node after this node. 
* @param newLink 
* a reference to the node that should appear after this node in the 
* linked list (or the null reference if there is no node after this node) 
* @postcondition 
* The link to the node after this node has been set to newLink. Any other 
* node (that used to be in this link) is no longer connected to this node. 
**/ 
public void setLink(DoubleNode newLink) 
{      
    link = newLink; 
} 
} 
+1

@ 선생님이 선생님의 책을 언급하셨습니까? 읽어주십시오. 또한 단위 테스트 작성을 시작하십시오. – Jayan

+1

코드에 더 많은 의견을 게시하십시오! – Bohemian

+0

작은 레코드를 삽입하거나 선택하는 것과 같은 기본 정렬 알고리즘을 사용하여 비교기 인터페이스도 확인하십시오. –

답변

3

생각

1 다음 목록은 내 코드입니다) 가장 간단한 경우 목록은 이미 정렬되어 있습니다.

,210

->를

2) 이제, "다음"경우를 고려 (즉, 당신이 크기 1)

목록 1 개 새로운 요소를 추가하는 경우 -> A A보다> C 인 경우 단순히 확인하실 수 있습니다

[지금, 나는 C를 추가하려고 하겠어] (예 : -> A -> C)

3) 다음과 같은 경우 일반화 할 수 있습니다. 삽입하고있는 것보다> 새로운 노드를 보게됩니다. - 2 개의 새로운에> C

는 대체 :

- -> A> C [추가 B]는

check 1: A (B > A) 
check 2: C (B < C) ! 

이것은 우리는 다음과 같은 링크를 대체 할 수 있음을 의미 링크, 1에서 A -> B, 또 다른 하나는 B -> C.

이렇게 삽입하면 귀하의 목록은 정렬 된 상태입니다.

구체적으로

당신은 따라서 걷고, 그리고 즉, "기억"각 DoubleNode을 목록의 beggining에서 시작, 응용 프로그램의 삽입 (..) 메소드를 수정하고 확인해야합니다 이전 DoubleNode가 목록의 끝에 도달 할 때까지 저장합니다. 또는 마지막 노드가 새 노드보다 <이고 현재 노드가 새 노드보다 큼을 확인합니다.

+0

대답 해 주셔서 감사합니다 ... 몇 년 전 이었지만! – user1282637