题解 | #从尾到头打印链表#
反转链表
http://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca
只需要三个变量 pre, cur,next,不需要额外空间,空间复杂度O(1),代码如下:
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode ReverseList(ListNode head) {
if (head == null || head.next == null){
return head;
}
ListNode pre = head;
ListNode cur = head.next;
ListNode next = cur.next;
pre.next = null; // 头节点指向null
while(next != null){
cur.next = pre;
pre = cur;
cur = next;
next = next.next;
}
cur.next = pre;
return cur;
}
}