数据结构 | 链表

反转链表

给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。
 

示例 1:


输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]
示例 2:


输入:head = [1,2]
输出:[2,1]

提示:

  • 链表中节点的数目范围是 [0, 5000]
  • -5000 <= Node.val <= 5000

迭代版:

  • 链表反转:在遍历链表时,将当前节点的 next 指针改为指向前一个节点。
  • pre结点:由于节点没有引用其前一个节点,因此必须事先存储其前一个节点。
  • curnode结点:在更改引用之前,还需要存储后一个节点。最后返回新的头引用。

/**
 * 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}
 */
 var reverseList = function(head) {
    let pre=null;//反转后的尾结点指向null
    let curnode=head;
    while(curnode){
        let next = curnode.next;//保存下一节点
        curnode.next=pre;//链表反转
        pre=curnode;//更新pre和curnode,即移动指针
        curnode=next;
    }
    return pre;
};

递归版:

从头结点开始递归到底,递归出口就是最后一个结点。最后一个节点作为反转后的头节点。

然后就是在每一层递归种进行反转的操作

image.png
/**
 * 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}
 */
 var reverseList = function(head) {
     //递归出口,返回最后一个结点作为反转后的头结点
     if(head===null || head.next===null)
        return head;
    //此处进入递归,递归一直遍历到尾结点时才返回
    let newhead=reverseList(head.next);
    //每一层递归操作,让head的下一个结点的next指向自己
    head.next.next=head;
    //head(转为尾结点)指向null,达到反转目的
    head.next=null;
    return newhead;

};
阅读剩余
THE END