LeetCode 206. 反转链表
题目
反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-linked-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解题思路
思路1-直接迭代处理,逐个反转;
思路2-使用递归方式;
总结:递归的方式比较绕,需要仔细想明白逻辑是怎么回事
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
| package leetcode;
public class LeetCode_0206 {
}
class ListNode_0206 { int val; ListNode_0206 next;
ListNode_0206(int x) { val = x; } }
class Solution_0206 {
public ListNode_0206 reverseList_1(ListNode_0206 head) { ListNode_0206 pre = null; ListNode_0206 next = null; while (head != null) { next = head.next; head.next = pre; pre = head; head = next; } return pre; }
public ListNode_0206 reverseList_2(ListNode_0206 head) { return reverse(null, head); }
private ListNode_0206 reverse(ListNode_0206 tail, ListNode_0206 head) { if (head == null) { return tail; } ListNode_0206 next = head.next; head.next = tail; return reverse(head, next); }
public ListNode_0206 reverseList_3(ListNode_0206 head) { if (head == null || head.next == null) { return head; } ListNode_0206 newHead = reverseList_3(head.next); head.next.next = head; head.next = null; return newHead; } }
|