다음은 Java를 이용하여 Single Linked List를 작성하는 방법에 대해 편집자가 공유한 방법입니다. 궁금한 점이 있으면 메시지를 남겨주세요.
먼저 노드 클래스를 정의합니다
1 2 3 4 5 6 7 8 9 10 11 12 | public class Node {
protected Node next;
public int data;
public Node( int data) {
this. data = data;
}
public void display() {
System. out. print ( data + " " );
}
}
|
로그인 후 복사
다음으로 단일 연결 목록을 정의하고 관련 메서드를 구현합니다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 | public class LinkList {
public Node first;
private int pos = 0;
public LinkList() {
this.first = null;
}
public void addFirstNode(int data) {
Node node = new Node(data);
node.next = first;
first = node;
}
public Node deleteFirstNode() {
Node tempNode = first;
first = tempNode.next;
return tempNode;
}
public void add(int index, int data) {
Node node = new Node(data);
Node current = first;
Node previous = first;
while (pos != index) {
previous = current;
current = current.next;
pos++;
}
node.next = current;
previous.next = node;
pos = 0;
}
public Node deleteByPos(int index) {
Node current = first;
Node previous = first;
while (pos != index) {
pos++;
previous = current;
current = current.next;
}
if (current == first) {
first = first.next;
} else {
pos = 0;
previous.next = current.next;
}
return current;
}
public Node deleteByData(int data) {
Node current = first;
Node previous = first;
while (current.data != data) {
if (current.next == null) {
return null;
}
previous = current;
current = current.next;
}
if (current == first) {
first = first.next;
} else {
previous.next = current.next;
}
return current;
}
public void displayAllNodes() {
Node current = first;
while (current != null) {
current.display();
current = current.next;
}
System.out.println();
}
public Node findByPos(int index) {
Node current = first;
if (pos != index) {
current = current.next;
pos++;
}
return current;
}
public Node findByData(int data) {
Node current = first;
while (current.data != data) {
if (current.next == null)
return null;
current = current.next;
}
return current;
}
}
|
로그인 후 복사
마지막으로 테스트 클래스를 통해 관련 테스트를 수행할 수 있습니다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | public class TestLinkList {
public static void main(String[] args) {
LinkList linkList = new LinkList();
linkList.addFirstNode(20);
linkList.addFirstNode(21);
linkList.addFirstNode(19);
linkList.add(1, 22);
linkList.add(2, 23);
linkList.add(3, 99);
linkList.displayAllNodes();
}
}
|
로그인 후 복사
이 시점에서 단일 링크 목록 작업 참고 사항은 여기에 있습니다.
위는 편집자가 소개한 Java 단일 연결 목록 구현 코드입니다. 궁금한 점이 있으면 메시지를 남겨주시면 편집자가 시간에 맞춰 답변해 드리겠습니다. . 또한 PHP 중국어 웹사이트를 지원해 주신 모든 분들께 감사드립니다!
Java 단일 연결 목록 구현 코드와 관련된 더 많은 기사를 보려면 PHP 중국어 웹사이트를 주목하세요!