算法通关村第二关——终于学会链表反转了

反转链表

leetcode206题

建立虚拟头节点辅助反转

第一反应,顺序遍历链表,每个节点用头插法,插入到新链表的头部,即可实现反转

为了方便后续循环操作,先从原链表摘出头节点,作为新链表的头节点

public ListNode reverseList(ListNode head) {
    if(head == null) return null;
    ListNode newlist;
    ListNode current = head;
    //先向新节点加入一个节点
    newlist = head;
    head = head.next;
    current.next = null;
    current = head;
    //开始头插法
    while(head != null) {
        head = head.next;
        current.next = newlist;
        newlist = current;
        current = head;
    }
    return newlist;
}

直接操作链表实现反转

大概看了一眼解析,类似于用三个指针,指向相邻的三个节点,然后通过指针直接调转三个节点的next

还是画个图吧

在这里插入图片描述

public ListNode reverseList(ListNode head) {
    if(head == null) return null;
    if(head.next == null) return head;
    ListNode pre = head, cur = head.next, next = head.next.next;
    //将头节点的指针置为null
    pre.next = null;
    //结合图理解
    cur.next = pre;
    while(next != null) {
        //三个指针后移
        pre = cur;
        cur = next;
        next = next.next;

        //反转cur方向
        cur.next = pre;
    }
    ListNode ans = cur;return ans;
}

要注意边界问题,em另外看了答案的代码,发现自己写的有点傻,又有边界问题,思路又不简洁

public ListNode reverseList(ListNode head) {
    ListNode prev = null;
    ListNodd curr = head;
    while(curr != null) {
        //在反转cur节点之前先给next赋值
        ListNode next = curr.next;
        curr.next = prev;
        prev = curr;
        curr = next;
    }
    return prev;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值