- 递归------ 消耗内存空间-栈,空间复杂度O(n)
// 直接递归实现核心代码片段
public void reverse(head){
// 递归终止条件
if(head.next == null){
print(head);
return;
}
// 下一层需要做的事儿
reverse(head.next);
// 本层需要做的事儿
print(head);
}
- 利用栈实现--------空间复杂度O(n)
// 采用栈进行存储实现核心代码片段
public void reverse(head){
Node cur = head;
// 将所有元素入栈
while(cur != null){
stack.push(cur);
cur = cur.next;
}
// 将所有元素出栈
while(!stack.isEmpty){
print(stack.poll);
}
}
- 链表翻转用两指针处理--------时间复杂度O(n),但是
原始链表结构被改变
// 翻转链表实现核心代码
public void reverse(head){
Node cur = head.next;
Node pre = head;
pre.next = null;
Node tmp = new Node();
// 翻转链表
while(cur != null){
tmp = cur.next;
cur.next = pre;
pre = cur;
cur = tmp;
}
// 输出
while(pre != null){
print(pre);
pre = pre.next;
}
}