Leetcode206:反转链表

一、题目

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

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

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

输入:head = []
输出:[]

二、题解

1.头插法

构造一个新链表,从旧链表中取出节点,一个个插入到新链表的头部,最后就逆序了。
在这里插入图片描述

public static Node reverseList1(Node head) {
    //新链表的头节点
    Node node = null;
    //遍历旧链表
    while (head != null) {
        //每次都创建一个新节点,放在新链表的头部(当前链表的next是之前的node)
        node = new Node(head.value, node);
        //让旧链表的头指针往下移动一位
        head = head.next;
    }
    return node;
}
2.双指针
  • 1.因为要改变指针的方向,会丢失掉原本next的指针,所以让next元素先暂存起来:ListNode temp = head.next;
  • 2.改变cur指针的指向(head指针)head.next = pre;
  • 3.让pre和cur同时向后移动 pre = head; head = temp;
  • 4.当cur指向到null时,遍历完毕 head!=null
    在这里插入图片描述
public Node reverseList(Node head) {
    Node pre = null;
    while(head!=null){
        //把当前节点的后一个节点暂存到temp
        Node temp = head.next;
        head.next = pre;
        pre = head;
        head = temp;
    }
    return pre;
}
3.递归

通过递归调用每次让头指针往后移,即相当于执行了head = head.next
在递归内部的操作把指针的指向改变,为了防止循环引用,在改变完当前节点的指向后,还要把前一个节点的指针指为空。
image.png

public static Node reverseList(Node head) {
    if (head == null || head.next == null) {
        return head;
    }
    //返回最后的节点
    Node node = reverseList(head.next);
    head.next.next = head;
    head.next = null;
    return node;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值