题解 | #反转链表#
反转链表
http://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca
先设三个变量:
now:当前结点
las:上一个节点
nex:下一个节点
这三个都是对于原链表来说的
我们只需要对每一个节点做:将now指向las,nex指向now
可以写出如下核心代码(循环,直至nex为空)
las=now;
now=nex;
nex=nex.next;
now.next=las;
每循环一次,原来的now指向las,nex指向now;然后las,now,nex整体后移一个结点。
空间复杂度(用head代替now节省空间):新开了las和now,所以是O(2)
时间复杂度:上述操作做了n-1次,K*O(n-1)即O(n)
完整代码:
public static ListNode ReverseList(ListNode head) {
if(head==null) return head;
ListNode nex=head.next;
ListNode las=null;
head.next=las;
while(nex!=null){
las=head;
head=nex;
nex=head.next;
head.next=las;
}
return head;
}
}