leetcode题解-206. Reverse Linked List

来源:互联网 发布:测绘数据泄密案例 编辑:程序博客网 时间:2024/05/16 11:35

题目:

Reverse a singly linked list.click to show more hints.Hint:A linked list can be reversed either iteratively or recursively. Could you implement both?

本题就是将链表翻转,按照提示可以根据循环和递归两种方式进行,比较简单不做过多解释,直接上代码:

    //循环法    public ListNode reverseList(ListNode head) {        ListNode cur=head, next=head, pre=null;        while(cur != null){            next = cur.next;            cur.next = pre;            pre = cur;            cur = next;        }        return pre;    }
    //递归法    public static ListNode reverseList1(ListNode head){        ListNode cur = head;        return dfs(cur, null);    }    public static ListNode dfs(ListNode cur, ListNode pre){        if(cur == null)            return pre;        ListNode next = cur.next;        cur.next = pre;        pre = cur;        cur = next;        return dfs(cur, pre);    }