206

2021-03-21  本文已影响0人  M1chaelY0ung

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;
    }
}
上一篇下一篇

猜你喜欢

热点阅读