链表翻转(栈)
算法过程描述为:
1.定义一个新的head
2.一直找到最后一个节点插入到head
...
时间复杂度为o(n+n-1+n-2+...+1) = o(n!)
...这种想法肯定是极度糟糕的
最好的还是基于栈的
1.依次入栈
2.出栈,构建链表
package List;
import Debug.Debug;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Stack;
/**
* 翻转链表
*/
public class OverturnList {
public ListNode overturnList(ListNode head){
ListNode newNode = new ListNode();
ListNode cur = newNode;
//1.push all nodes in list to stack
Stack<ListNode> stack = pushStack(head);
while (!stack.isEmpty()){
ListNode temp = stack.pop();
//2.insert the top element of stack into the list with newNode head;
insert(cur,temp);
//指向下一个节点...
cur = cur.next;
}
//3.return the list with newNode head;
return newNode.next;
}
/**
* 向 frontNode 之后插入value 节点
* @param frontNode
* @param value
*/
private void insert(ListNode frontNode, ListNode value){
ListNode cache = frontNode.next;
frontNode.next = value;
value.next = cache;
}
private Stack<ListNode> pushStack(ListNode head){
Stack<ListNode> stack = new Stack<ListNode>();
ListNode cur = head;
while (cur!= null){
stack.push(cur);
cur = cur.next;
}
return stack;
}
}
不借助栈
如果有一天,有人告诉你(比如那个让你又爱又恨的面试官)让你不用栈,你会怎么破?
参考这一篇知乎:
https://zhuanlan.zhihu.com/p/240694166
值得注意的是,对于链表来讲,翻转,是非常重要的一个算法
如果你学习链表而不学习算法,相当于得起形而不得其神。