力扣 206: 反转链表
定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。
示例一
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
迭代解法
var reverseList = function(head) {
let newList = new ListNode(-1)
while(head != null){
let next = head.next
head.next = newList.next
newList.next = head
head = next
}
return newList.next
};
递归解法
var reverseList = function(head) {
if(head == null || head.next == null) return head
let lastHead = reverseList(head.next)
head.next.next = head // 对下一个指向赋值
head.next = null // 清除自身原来的指向
return lastHead
};
本题来源于力扣,更多解题思路请跳到本题