[leetcode-JavaScript]---206.反转链表

775 阅读1分钟

反转一个单链表。

示例:
    输入: 1->2->3->4->5->NULL
    输出: 5->4->3->2->1->NULL
  • 思考

在遍历列表时,将当前节点的 next 指针改为指向前一个元素。由于节点没有引用其上一个节点,因此必须事先存储其前一个元素。 在更改引用之前,还需要另一个指针来存储下一个节点。不要忘记在最后返回新的头引用!

  • 迭代法
/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} head
 * @return {ListNode}
 */
var reverseList = function(head) {
    if(head===null || head.next===null){
        return head;
    }
    let temp=null;
    /**
     * 新的头节点
     */
    let newHead=null;
    while(head !=null){
        temp=head;/**缓存当前节点 */
        head=head.next;/**缓存下一个节点 */
        temp.next=newHead;/**缓存的当前节点的next指向新的头节点 */
        newHead=temp;
    }
    return newHead;
};

最后

封面大图来自 必应壁纸,侵权删