反转链表

/**

  • 反转链表
  • 输入: 1->2->3->4->5->NULL
  • 输出: 5->4->3->2->1->NULL
    */
class Solution {
//    public static ListNode reverseList(ListNode head) {
//        ListNode prev = null;
//        ListNode cur = head;
//        while(cur != null){
//            ListNode next = cur.next;
//            cur.next = prev;
//            prev = cur;
//            cur = next;
//        }
//        return prev;
//    }
    //递归版本
    public static ListNode reverseList(ListNode head){
        if(head == null || head.next == null){
            return head;
        }
        ListNode newHead = reverseList(head.next);
        head.next.next = head;
        head.next = null;
        return newHead;
    }

    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        head.next = new ListNode(2);
        head.next.next = new ListNode(3);
        head.next.next.next = new ListNode(4);
        head.next.next.next.next = new ListNode(5);
        head.next.next.next.next.next = null;
        ListNode result = reverseList(head);
        ListNode p = result;
        while(p != null){
            System.out.print(p.val + "->");
            p = p.next;
        }
    }
}
posted @ 2022-01-02 15:58  zjy4fun  阅读(19)  评论(0编辑  收藏  举报