LeetCode 206. Reverse Linked List(翻转链表)

来源:互联网 发布:浅野菌子淘宝 编辑:程序博客网 时间:2024/05/16 04:55

原题网址:https://leetcode.com/problems/reverse-linked-list/

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?

方法一:迭代。

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { val = x; } * } */public class Solution {    public ListNode reverseList(ListNode head) {        if (head == null || head.next == null) return head;        ListNode current = head.next;        ListNode prev = head;        prev.next = null;        while (current.next != null) {            ListNode next = current.next;            current.next = prev;            prev = current;            current = next;        }        current.next = prev;        return current;    }}

方法二:递归。

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { val = x; } * } */public class Solution {    private ListNode reversed;    private void reverse(ListNode prev, ListNode node) {        if (node == null) return;        reversed = node;        ListNode next = node.next;        node.next = prev;        reverse(node, next);    }    public ListNode reverseList(ListNode head) {        if (head == null || head.next == null) return head;        reverse(null, head);        return reversed;    }}


0 0