java 단일 체인 테이블 역전 실현
class Node {
Node next;
String name;
public Node(String name) {
this.name = name;
}
/**
*
*/
public void show() {
Node temp = this;
do {
System.out.print(temp + "->");
temp = temp.next;
}while(temp != null);
System.out.println();
}
/**
* , : , StackOverflowError
* @param n
* @return
*/
public static Node recursionReverse(Node n) {
long start = System.currentTimeMillis();
if(n == null || n.next == null) {
return n;
}
Node reverseNode = recursionReverse(n.next);
n.next.next = n;
n.next = null;
System.out.println(" :" + (System.currentTimeMillis() - start) + "ms...");
return reverseNode;
}
/**
*
* @param n
* @return
*/
public static Node loopReverse(Node n) {
long start = System.currentTimeMillis();
if(n == null || n.next == null) {
return n;
}
Node pre = n;
Node cur = n.next;
Node next = null;
while(cur != null) {
next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
n.next = null;
n = pre;
System.out.println(" :" + (System.currentTimeMillis() - start) + "ms...");
return pre;
}
@Override
public String toString() {
return name;
}
public static void main(String[] args) {
int len = 10;
Node[] nodes = new Node[len];
for(int i = 0; i < len; i++) {
nodes[i] = new Node(i + "");
}
for(int i = 0; i < len - 1; i++) {
nodes[i].next = nodes[i+1];
}
/* try {
Thread.sleep(120000);
} catch (InterruptedException e) {
e.printStackTrace();
}*/
Node r1 = Node.loopReverse(nodes[0]);
r1.show();
Node r = Node.recursionReverse(r1);
r.show();
}
}
인용하다
총결산
인용하다
귀환과 순환에 대해 순환 실현을 추천합니다. 귀환은 단일 체인표가 너무 크면 나타날 수 있습니다.
StatckOverflowError, 반복은 메소드 호출과 관련되며, 성능에서도 루프 구현보다 약합니다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
단일 체인 테이블 -- - 반복 설정, 반복 반전, 반복 인쇄텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.