206. Reverse Linked List(Java)

来源:互联网 发布:macbookair软件下载 编辑:程序博客网 时间:2024/05/20 09:22

Reverse a singly linked list.

A linked list can be reversed either iteratively or recursively. Could you implement both?

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { val = x; } * } */

代码1:recursive solution

public class Solution {    public ListNode reverseList(ListNode head) {        return reverseListInt(head, null);    }    private ListNode reverseListInt(ListNode head, ListNode newNext) {        if (head == null)             return newNext;        ListNode oldNext = head.next;        head.next = newNext;        return reverseListInt(oldNext, head);    }}

代码2:iterative solution

public class Solution {    public ListNode reverseList(ListNode head) {        ListNode newNext = null;        while (head != null) {            ListNode oldNext = head.next;            head.next = newNext;            newNext = head;            head = oldNext;        }        return newNext;    }}
原创粉丝点击