单链表翻转是一道很简单的题目,但是对于coding能力较弱的同学来说,还是有难度的,这里提供一个解决方案,空间复杂度为O(1)。
public Node reverList(Node head){
if(head == null){
return null;
}
Node cur = head,pre=null;
while(cur != null){
Node tmp = cur.next;
cur.next = pre;
pre = cur;
if(tmp == null){
pre = cur;// 保留新头
}
cur = tmp;
}
return pre;
}
想当年我面webank 的时候写了15分钟都还没写出来,现在4分钟内写完调试完!!!
我变秃了,也变强了!!!