N 번째 인덱스 에서 LinkedList에 노드를 삽입하는 방법을 만들었습니다 . 이 코드는 0 번째 위치를 제외한 모든 위치에서 잘 작동합니다. 아래 코드를 검토하고 무엇이 잘못되었는지 알려주세요. 아래 코드에는 두 가지 삽입 방법이 있습니다.
insert(int data)
: 새 노드를 추가하는 데 사용됩니다.insertAtNthPositon(int position, int data)
: N 번째 위치에 요소를 삽입하는 데 도움이됩니다.public class LinkedList {
Node head;
static class Node {
int data;
Node next;
}
public void insert(int data) {
Node new_node = new Node();
new_node.data = data;
new_node.next = null;
if (head == null) {
head = new_node;
} else {
Node n = head;
while (n.next != null) {
n = n.next;
}
n.next = new_node;
}
}
public void insertAtNthPositon(int position, int data) {
Node new_node = new Node();
new_node.data = data;
Node current_node = head;
int i = 0;
if (position == 0) {
new_node.next = current_node.next;
head = new_node;
current_node = current_node.next;
}
while (i < position - 1) {
current_node = current_node.next;
i++;
}
new_node.next = current_node.next;
current_node.next = new_node;
}
public static void main(String[] arg) {
LinkedList ls = new LinkedList();
ls.insert(6);
ls.insert(7);
ls.insert(9);
ls.insertAtNthPositon(1, 100);
ls.show();
}
private void show() {
Node current = head;
StringBuilder sb = new StringBuilder();
do {
sb.append(current.data);
sb.append("->");
current = current.next;
} while (current != null);
sb.append("null");
System.out.println(sb.toString());
}
}
산출:
6-> 100-> 7-> 9-> null
내가 제안한대로 : [at : if (position == 0)] new_node.next를 current_node.next가 아닌 current_node로 설정해야합니다-> 이것이 항상 0이 아닌 인덱스 1에서 시작하는 이유입니다.
public void insertAtNthPositon(int position, int data){
Node new_node = new Node();
new_node.data =data;
Node current_node = head;
int i = 0;
if (position == 0){
**new_node.next = current_node;** <instead of current_node.next>
head = new_node;
current_node = current_node.next;
}
while(i < position - 1){
current_node = current_node.next;
i++;
}
new_node.next = current_node.next;
current_node.next = new_node;
}
BTW- ls.insertAtNthPositon (1, 100); 인덱스 1에 100을 삽입하면 ls.insertAtNthPositon (0, 100); '100'이 첫 번째가 되려면.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다