Reverse a singly linked list.
Example:
Input: 1->2->3->4->5->NULL Output: 5->4->3->2->1->NULL
Follow up:
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; } * } */ class Solution { public ListNode reverseList(ListNode head) { if(head == null) return null; ListNode res = new ListNode(head.val); head = head.next; while(head != null){ ListNode z = res; res = new ListNode(head.val); res.next = z; head = head.next; } return res; } }
解法二:递归(看不懂。。。)
public ListNode reverseList(ListNode head) { if (head == null || head.next == null) return head; ListNode p = reverseList(head.next); head.next.next = head; head.next = null; return p; }
leetcode 206. Reverse Linked List
原文:https://www.cnblogs.com/jamieliu/p/10349077.html