나는 연결된 목록에 문자열을 삽입해야하는 연습장이 있습니다. 문자열은 다음과 같다 가정 : 병합 정렬 후Java의 문자열 병합 정렬 - 연결된 목록
"Java Coding Is Great"
은, 링크 된 목록은 그 같이 가정한다 :
coding >>> great >>> is >>> java.
문제는 내 병합 분류 코드에서 나는 다음을받을 것입니다 :
great >> is >> java >> coding
모든 단어가 정렬되지만 모든 단어는 정렬됩니다 (원래 목록의 헤드).
두 가지 클래스가 있습니다 : TextList와 WordNode. 연결리스트의 머리의 주소 :
String _word; WordNode _next; //an address to the next link
TextList 클래스는 하나의 속성이 있습니다
WordNode 클래스는 두 개의 속성이 있습니다
WordNode _head;
나는 생성자가있는 I 문자열을 링크 된 목록에 임의로 삽입하십시오. 결국 그것은 목록을 병합 시작합니다. 이 알고리즘은이 훈련에 사용됩니다.
public TextList(String text){
String s=""; int index=text.length();
//we will stop at the end of the String.
for (int i=text.length()-1; i>=0; i--){
//if we reached a space, insert each string in appropriate order,
//the first word is the head of the string and last word points to null.
if (!(text.charAt(i)>='a' && text.charAt(i)<='z')){
s=text.substring(i,index);
_head=new WordNode(s,_head);
s="";
index=i;
}
if (i==1){
s=text.substring(i-1,index);
_head=new WordNode(s,_head);
}
}
//start merge sotring the list.
this._head=this._head.mergeSort();
}
병합 정렬 방법 : 머지 소트가 합병 및 분할 (이들은 WordNode 클래스에)
병합 정렬 방법
public WordNode mergeSort(){
return mergeSort(this);
}
private WordNode mergeSort(WordNode h){
// Sort h by recursively splitting and merging
if (h==null || h._next==null)
return h;
else{
WordNode evens=h.splitOdds();
WordNode odds=h.splitEvens();
return mergeSort(odds).merge(mergeSort(evens));
}
}
가
private WordNode merge(WordNode h){
//method merges this's list with h's list
//if h is null, just return this.
if (h==null){
return this;
}
if (this._word.compareTo(h._word)<0){
if (this._next==null)
return new WordNode(this._word,h);
else
return new WordNode(this._word,this._next.merge(h));
}
else
return new WordNode (h._word, merge(h._next));
}
방법 병합
분할 방법 : 짝수 위치에 하나, 홀수 위치에 하나씩.
private WordNode splitOdds(){
boolean flag=true;
WordNode odds=null;
WordNode ptr=this;
while (ptr!=null){
if(flag)
odds=new WordNode(ptr._word,odds);
ptr=ptr.getNext();
flag=!flag;
}
return odds;
}
//MUST BE INITILIZED ON HEAD
private WordNode splitEvens(){
boolean flag=true;
WordNode evens=null;
WordNode ptr=this._next;
while (ptr!=null){
if (flag)
evens=new WordNode(ptr._word,evens);
ptr=ptr.getNext();
flag=!flag;
}
return evens;
}
무엇이 잘못 되었나요? 불행히도 세 번째 클래스 인, 을 사용할 수 없으며 목록 시작 부분이나 끝 부분에 포인터를 사용할 수 없습니다.
동일한 질문을 여러 번 게시하면 답을 찾는 데 도움이되지 않습니다. 둘 중 하나를 삭제하고 답변을 기다리십시오. – BackSlash
@BackSlash - 코드가 거의 작동하므로 여기에서 실질적인 진전을 보았습니다. 주의를 기울여 주셔서 감사합니다. 이전 질문을 삭제하려면 어떻게해야합니까? – Alan
삭제하지 마십시오. ** ** ** 질문을 삭제하고, ** 이전 세부 정보를 ** 새로운 세부 정보로 업데이트하십시오. – BackSlash