206

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

相关阅读更多精彩内容

友情链接更多精彩内容