/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
1、逐个断键,将后一个节点放到前面
var reverseList = function(head) {
var len = getLen(head)
var h = head
var pre = head
while(len>0){
var temp = h.next
h.next = null
h.next = temp.next
temp.next = null
temp.next = pre
pre = temp
len--
}
return pre
};
function getLen(p){
var length = 0
while(p != null){
length ++
p=p.next
}
return length-1
}
2、与1类似但代码较少
var reverseList = function(head) {
var pre = null
var current = head
while(current != null){
var temp = current.next
current.next = pre
pre = current
current = temp
}
return pre
};