2012-01-05 3 views
1

여기버블 정렬은

public void sortStudentsAlphabeticallyByFirstName() 
{ 
    StudentNode unsorted = tail; 
    StudentNode current = header; 
    while(current != null) 
    { 
     while(current != unsorted) 
     { 
      int result = (current.nextNode().getFirstName()).compareToIgnoreCase(current.getFirstName()); 
      if(result < 0) 
      { 
       StudentNode temp = current; 
       current = current.nextNode(); 
       current.setNext(temp); 
      } 
     } 
     current = current.nextNode(); 
     unsorted = unsorted.prevNode(); 
    } 
} 

문제가 메소드의 실행을 중지하지 않는 그냥 계속 실행 중지하지 않고 문제가 어디 있는지 모르겠어요 실행될 때 .

+3

자, 내부 while 루프를 고려해보십시오. 결코 false를 반환 할 수없는 상황이 있는지 확인하십시오. 그것은 꽤 분명합니다 - 당신은 그것을보아야합니다. 일반적으로, 이와 같은 문제에서 디버그 출력은 가장 좋은 친구입니다. 내부 while 루프 내에서 현재 요소를 인쇄해야하며, 무엇이 잘못되었는지를 빨리 알 수 있습니다. 이것은 숙제처럼 보이기 때문에, 나는 그것에 맡길 것이다. – EboMike

+0

사용하는 데이터 유형을 확인할 수 있도록 코드를 완성 할 수 있습니까? –

+0

그래서 집에서 일하는게 어때요? – Viele

답변

1

우리의 링크 목록은 A, C, B와 D 노드가 좋습니다. 루프

current = C; 

그래서이 코드를 사용하는 동안 두 번째에 입력 할 말 :

temp = current; // i.e. temp = C as current = C 
current = current.next(); // say current = B now and temp = C 
current.setNext(temp); // here B's next is set to C 
         // but you forgot A's next is C in the example, now since B 
         // is taking it's place so A's next must point to B 
         // B's next must point to C and C's next must point to D. 

그래서이 단계를 잊었 것 같아 당신이 후 다음 노드로 현재 이동

그것, 임시 직원 및 현재는 교환 할 것이다. 그러나 예에서 임시 A에 앞의 예는 B로 가리켜 야합니다. B가 D로 가리키고 있기 때문에 C를 스와핑 한 후에 C가 D를 가리켜 야하고 B가 가리켜 야합니다. C (즉, 세 번째 줄에 무슨 짓을했는지.)

편집 전체 작업 코드는 자세한 내용이 추가되었습니다.

import java.io.*; 

class Node 
{ 
public Node previous; 
public String value; 
public Node next; 
} 

public class LinkedList 
{ 
private BufferedReader br ; 
private String str; 
private int totalNodes; 

private Node current, previous, temp, head, tail; 

public LinkedList() 
{ 
    br = new BufferedReader(new InputStreamReader(System.in)); 
    current = previous = temp = head = tail = null; 
    totalNodes = 0; 
} 

public static void main(String[] args) 
{ 
    LinkedList ll = new LinkedList(); 
    ll.menu(); 
} 

private void menu() 
{ 
    boolean flag = true; 
    int choice = 0; 
    while(flag) 
    { 
     System.out.println("--------------------------------------------------"); 
     System.out.println("---------------------MENU-----------------------"); 
     System.out.println("Press 1 : To ADD Node at the END."); 
     System.out.println("Press 2 : To ADD Node at the BEGINNING."); 
     System.out.println("Press 3 : To Add Node in BETWEEN the List."); 
     System.out.println("Press 4 : To SORT the List"); 
     System.out.println("Press 5 : To DISPLAY the List."); 
     System.out.println("Press 6 : To EXIT the Program."); 
     System.out.println("--------------------------------------------------"); 
     System.out.print("Please Enter your choice here : "); 
     try 
     { 
      str = br.readLine(); 
      choice = Integer.parseInt(str); 
      if (choice == 6) 
      { 
       flag = false; 
      } 
      accept(choice); 
     } 
     catch(NumberFormatException nfe) 
     { 
      System.out.println("OUCH!, Number Format Exception, entotalNodesered."); 
      nfe.printStackTrace(); 
     } 
     catch(IOException ioe) 
     { 
      System.out.println("OUCH!, IOException, entotalNodesered."); 
      ioe.printStackTrace(); 

     } 
    } 
} 

private void accept(int choice) 
{ 
    switch(choice) 
    { 
     case 1: 
      addNodeToListAtStart(); 
      break; 
     case 4: 
      sortListBubble(); 
      break; 
     case 5: 
      displayList(); 
      break; 
     case 6: 
      System.out.println("Program is Exiting."); 
      break; 
     default: 
      System.out.println("Invalid Choice.\nPlease Refer Menu for further Assistance."); 
    } 
} 

private void addNodeToListAtStart() 
{ 
    if (head != null) 
    { 
     current = new Node(); 
     System.out.print("Enter value for the New Node : "); 
     try 
     { 
      str = br.readLine(); 
     } 
     catch(NumberFormatException nfe) 
     { 
      System.out.println("OUCH!, Number Format Exception, entotalNodesered."); 
      nfe.printStackTrace(); 
     } 
     catch(IOException ioe) 
     { 
      System.out.println("OUCH!, IOException, entotalNodesered."); 
      ioe.printStackTrace();    
     } 
     current.previous = tail; 
     current.value = str; 
     current.next = null; 
     tail.next = current; 
     tail = current; 
    } 
    else if (head == null) 
    { 
     current = new Node(); 
     System.out.print("Enter value for the New Node : "); 
     try 
     { 
      str = br.readLine(); 
     } 
     catch(NumberFormatException nfe) 
     { 
      System.out.println("OUCH!, Number Format Exception, entotalNodesered."); 
      nfe.printStackTrace(); 
     } 
     catch(IOException ioe) 
     { 
      System.out.println("OUCH!, IOException, entotalNodesered."); 
      ioe.printStackTrace();    
     } 
     current.previous = null; 
     current.value = str; 
     current.next = null;    
     head = current; 
     tail = current; 
    } 
    totalNodes++; 
} 

private void displayList() 
{ 
    current = head; 
    System.out.println("----------DISPLAYING THE CONTENTS OF THE LINKED LIST---------"); 
    while (current != null) 
    { 
     System.out.println("******************************************"); 
     System.out.println("Node ADDRESS is : " + current); 
     System.out.println("PREVIOUS Node is at : " + current.previous); 
     System.out.println("VALUE in the Node is : " + current.value); 
     System.out.println("NEXT Node is at : " + current.next); 
     System.out.println("******************************************"); 
     current = current.next; 
    } 
} 

private boolean sortListBubble() 
{ 
    // For Example Say our List is 5, 3, 1, 2, 4 
    Node node1 = null, node2 = null; // These will act as reference. for the loop to continue 
    temp = head; // temp is set to the first node. 

    if (temp == tail || temp == null) 
     return false; 

    current = temp.next; // current has been set to second node. 

    for (int i = 0; i < totalNodes; i++) // this loop will run till whole list is not sorted. 
    { 
     temp = head; // temp will point to the first element of the list. 
     while (temp != tail) // till temp won't reach the second last, as it reaches the last element loop will stop. 
     { 
      if (temp != null) 
       current = temp.next; 
      while (current != null) // till current is not null. 
      { 
       int result = (temp.value).compareToIgnoreCase(current.value); 
       if (result > 0) // if elment on right side is higher in value then swap. 
       { 
        if (temp != head && current != tail) // if nodes are between the list. 
        { 
         current.previous = temp.previous; 
         (temp.previous).next = current; 
         temp.next = current.next; 
         (current.next).previous = temp;      
         current.next = temp; 
         temp.previous = current; 
        } 
        else if (current == tail) // if nodes to be swapped are second last and last(current) 
        { 
         temp.next = current.next; 
         current.previous = temp.previous; 
         if (temp.previous != null) 
          (temp.previous).next = current; 
         else 
          head = current; 
         temp.previous = current; 
         current.next = temp; 
         tail = temp; 
        } 
        else if (temp == head) // if the first two nodes are being swapped. 
        { 
         temp.next = current.next;      
         (current.next).previous = temp; 
         current.previous = temp.previous; 
         temp.previous = current; 
         current.next = temp; 
         head = current; 
        } 
        current = temp.next; // since swapping took place, current went to the left of temp, that's why 
                // again to bring it on the right side of temp. 
       } 
       else if (result <= 0) // if no swapping is to take place, then this thing 
       { 
        temp = current; // temp will move one place forward 
        current = current.next; // current will move one place forward 
       }          
      } 
      if (temp != null) 
       temp = temp.next; 
      else // if temp reaches the tail, so it will be null, hence changing it manually to tail to break the loop. 
       temp = tail; 
     } 
    } 
    return true; 
} 
} 

잘하면 도움이 될 수 있기를 바랍니다.

감사합니다.

+0

O.k'StudentNode temp = current;로 변경했습니다. StudentNode next = current.nextNode(); StudentNode previous = current.prevNode(); StudentNode nextNext = next.nextNode(); current = current.nextNode(); current.setNext (temp); temp.setNext (nextNext); nextNext.setPrev (temp); previous.setNext (current); temp.setPrev (현재); 전류.setPrev (이전); ' –

+0

하지만 여전히 계속 실행 중입니다. (서식을 지정해 주셔서 감사합니다) –

+0

@DaveShaw : 내가 뭘 잘못하고 있었는지, 제 답변을 좀 더 편집 중입니다. 문안 인사 –

1

나는 거품 정렬 알고리즘 보았다 때문에 그것은 오랜 시간이되었습니다 만, 다음과 같은 부분은

StudentNode temp = current; 
current = current.nextNode(); 
current.setNext(temp); 

는 노드 A를 시작 말해 잘못된 것 같다 -> B -> C (여기서 A = 현재) . 당신은 current = B (2 호선), current.next = A로 끝납니다,하지만 당신의 next을 대체하지도 current.next.next 다시 현재 당신의 temp 변수