링크 된 목록 2를 링크 된 목록 1의 끝에 병합해야하는 코드에서 누락 된 부분을 찾아 내려고했습니다. 바로 지금 두 번째 목록의 마지막 요소를 가져 오는 중입니다. 그걸 돌려 줬어.Java를 사용하여 두 개의 연결된 목록을 병합
내가 사용하려고했던 논리는 첫 번째 목록 (L1)을 걷고 그 요소를 하나씩 new_list에 추가 한 다음 두 번째 목록 (L2)에 대해 동일하게 처리하는 것입니다. L1. 나는 또한 L1 또는 L2를 수정하는 것을 피하려고 노력하고 있는데, 이것이 내가 왜 new_list를 만들었는지에 대한 것이다.
도움을 주시면 감사하겠습니다.
public NodeList(int item, NodeList next) {
this.item = item;
this.next = next;
}
public static NodeList merge(NodeList l1, NodeList l2) {
NodeList new_list = new NodeList(l1.item, l1.next);
NodeList new_list2 = new NodeList(l2.item, l2.next);
while (true) {
if (new_list.next == null) {
if (new_list2.next == null) {
return new_list;
}
else {
new_list.next = new NodeList(new_list2.next.item, new_list2.next.next);
new_list2 = new_list2.next;
}
}
else {
new_list.next = new NodeList(new_list.next.item, new_list.next.next);
new_list = new_list.next;
}
}
}
귀하의 while 루프는 결코 종료되지 않습니다 –
그것은 'Node'와'NodeList' 개념을 함께 섞어 놓은 것 같습니다. –
@SeanPatrickFloyd 두 목록이 모두 null이면 코드는 호출하는 메서드로 돌아갑니다. – azurefrog