问题:如何实现一个高效的单向链表逆序输出?
出题人:阿里巴巴出题专家:昀龙/阿里云弹性人工智能负责人
参考答案:下面是其中一种写法,也可以有不同的写法,比如递归等。供参考。
这道题目中我们要对一个链表进行逆序,因为链表是没有下标的,所以我们只能用节点的next指向来反转。 Java参考代码如下:
package com.tntxia.basic;
import java.util.Stack;
class Solution<T> {
public LinkNode<T> reverse(LinkNode<T> head) {
if (head == null || head.next == null) {
return head;
}
LinkNode<T> currentNode = head;
Stack<LinkNode<T>> stack = new Stack<>();
while (currentNode != null) {
stack.push(currentNode);
LinkNode<T> tempNode = currentNode.next;
currentNode.next = null;
currentNode = tempNode;
}
head = stack.pop();
currentNode = head;
while (!stack.isEmpty()) {
currentNode.next = stack.pop();
currentNode = currentNode.next;
}
return head;
}
}
public class LinkNode<T>{
T val;
public LinkNode(T val) {
this.val = val;
}
LinkNode<T> next;
public void print() {
LinkNode<T> current = this;
while (current != null){
System.out.println(current.val);
current = current.next;
}
}
public static void main(String[] args) {
Solution<Integer> sol = new Solution<Integer>();
LinkNode<Integer> head = null;
LinkNode<Integer> current = null;
for(int i = 1;i<=100;i++) {
if (current == null) {
current = new LinkNode<Integer>(i);
head = current;
continue;
}
current.next = new LinkNode<Integer>(i);
current = current.next;
}
head.print();
head = sol.reverse(head);
head.print();
}
}