反转链表

半腔热情 提交于 2020-02-13 02:06:33

问题: 分别用递归和非递归方式来实现反转链表。

思路1: 递归。

java代码:

ListNode reverseList(ListNode head,ListNode newHead){
        if(head==null||head.next==null){
            newHead=head;
            return head;
        }
        ListNode pre=reverseList(head.next,newHead);
        pre.next=head;
        head.next=null;
        return head;
    }

思路2: 非递归。
java代码:

ListNode reverseList(ListNode head){
        ListNode dummy=new ListNode(0);
        dummy.next=head;
        if(head==null)
            return head;
        ListNode curr=head.next;
        head.next=null;
        while(curr!=null){
            ListNode next=curr.next;
            curr.next=dummy.next;
            dummy.next=curr;
            curr=next;
        }
        return dummy.next;
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!