leetcode 206. Reverse Linked List
Posted jamieliu
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode 206. Reverse Linked List相关的知识,希望对你有一定的参考价值。
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的主要内容,如果未能解决你的问题,请参考以下文章
Leetcode 206 Reverse Linked List 链表
LeetCode 206 Reverse Linked List
Leetcode 206: Reverse Linked List
[LeetCode]206. Reverse Linked List
206. Reverse Linked List(LeetCode)
Leetcode92. Reverse Linked List II && 206. Reverse Linked List