Leetcode - Reverse Linked List

My code:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode reverseList(ListNode head) {
        if (head == null || head.next == null)
            return head;
        // /** iterative */
        // ListNode pre = head;
        // ListNode curr = head.next;
        // while (curr != null) {
        //     ListNode temp = curr.next;
        //     curr.next = pre;
        //     pre = curr;
        //     curr = temp;
        // }
        // head.next = null;
        // return pre;
        /** recursive */
        ListNode tail = head;
        while (tail.next != null)
            tail = tail.next;
        reverse(head);
        return tail;
    }
    
    private ListNode reverse(ListNode head) {
        if (head == null || head.next == null)
            return head;
        ListNode pre = reverse(head.next);
        pre.next = head;
        head.next = null;
        return head;
    }
}

这道题目用两种方法实现了反转链表。
一种是直接遍历,一边遍历一边反转。
一种是,用递归实现反转。

Anyway, Good luck, Richardo!

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容