이 코드는 자바 LinkedList 구현에서 가져온 것입니다.이 메소드는 목록의 색인 포인트에 문자열 요소를 추가하고 내 CS 도서 중 하나에서 가져옵니다.Java Linked List 포인터 혼동
링크 된 목록 클래스는 2 개 글로벌 private 변수
Node first;
Node last;
public void add(int index, String e) {
if (index < 0 || index > size()) {
String message = String.valueOf(index);
throw new IndexOutOfBoundsException(message);
}
// Index is at least 0
if (index == 0) {
// New element goes at beginning
first = new Node(e, first);
System.out.println("ran");
if (last == null)
last = first;
return;
}
// Set a reference pred to point to the node that
// will be the predecessor of the new node
Node pred = first;
for (int k = 1; k <= index - 1; k++) {
pred = pred.next;
}
// Splice in a node containing the new element
pred.next = new Node(e, pred.next);
System.out.println(toString());
// Is there a new last element ?
if (pred.next.next == null)
System.out.println("ran");
last = pred.next;
}
내 질문
을 가지고 내가 Node first, last
이
당신이 알을 가지고 있다고 가정 해보십시오. 그런 다음 요소 "4"인덱스에 3
그래서, 목록이 좋아하는 ["1","2","3","4","7","4","5,"6"]
보이는 추가,하지만 추가 방법의 코드를보고하는 나는 방법을 모른다
["1","2","3","7","4","5,"6"]
과 같은 표준시 처음으로 또는 마지막 노드 포인터가 업데이트됩니다. 인덱스가 0이 아닌 마지막이 변경되지 않기 때문에 내 마음에 이러한 실행 코드의 유일한 조각 때문에
편집
노드 first
는 toString 메소드에서 사용되는 객체 (미도시)를 추가하기 전에 수집
// Set a reference pred to point to the node that
// will be the predecessor of the new node
Node pred = first;
for (int k = 1; k <= index - 1; k++) {
pred = pred.next;
}
// Splice in a node containing the new element
pred.next = new Node(e, pred.next);
System.out.println(toString());
분명히하려면이 추가 메서드를 테스트하고 작동하지 않았다. – cheesey