206

作者: M1chaelY0ung | 来源:发表于2021-03-21 17:14 被阅读0次

Q:反转一个单链表。

示例:

输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-linked-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
A:
1,反转,将第一个元素置于最后,然后通过循环将下一个元素放置到链表首位(即preview)

class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode preview = null;
        ListNode current = head;
        while(current != null){
            ListNode next = current.next;
            current.next = preview;
            preview = current;
            current = next;
        }     
        return preview;
    }
}

2,通过递归,末尾元素,由3->4->5调整为3->4<-5,4为末尾元素,再通过3和4之间的指针关系,调整为2->3<-4<-5

class Solution {
    public ListNode reverseList(ListNode head) {
        if(head == null || head.next == null){
            return head;
        }
        ListNode node = reverseList(head.next);   
        head.next.next = head;
        head.next = null;
        return node;
    }
}

相关文章

  • 10个不为人知的黑科技网站,每个都值得你去收藏

    1: 206云解析 https://206dy.com/ 206云解析是一个实用的视频解析网站。 它支持7个主流的...

  • Leetcode PHP题解--D78 206. Reverse

    D78 206. Reverse Linked List 题目链接 206. Reverse Linked Lis...

  • 206

    206 坐着坐着 就老了 注:206,即广州的206路公交车。原写于2016年3月14日。其时,工作已换至芳村,住...

  • 2017-06-26

    yth206

  • 2018-07-04

    4号楼,206

  • 中波对照波斯诗歌《鲁拜集》连载44

    《鲁拜集》206 روزی بینی مرا تو مست افتاده بر پای تو سر نهاده پ...

  • 206

    也不知道是第几天了 今天早上挺累的 不过还好 寄了快递 老师也没有讲什么 下午也还好 给黄瓜定了生日礼物 晚上复习...

  • 206

    打包工汉嘉也曾有过真正的Love story。 如今的他会穿着被屠宰场的包肉纸弄得血迹斑斑的工作服,带着浑身的臭味...

  • 206

    二百零六块骨头 仿佛二百零六把镰刀 天地长久地,合在一起 人就长久地,走 把天地割开 把飞禽从走兽的脊背上割下 割...

  • 206

    E206 President Barack Obama, seeking to sell the Iran nuc...

网友评论

      本文标题:206

      本文链接:https://www.haomeiwen.com/subject/jitocltx.html