Day01

迭代+递归

 1 package LeetCode;
 2 
 3 public class L1_ReverseLinkedlist {
 4 
 5     static class ListNode {
 6         int val;
 7         ListNode next;
 8 
 9         public ListNode(int val, ListNode next) {
10             this.val = val;
11             this.next = next;
12         }
13     }
14 
15 //迭代
16     public static ListNode iterats(ListNode head) {
17         ListNode prev = null;
18         ListNode next = null;
19         ListNode curr = head;
20         while ( curr != null) {
21             next = curr.next;
22             curr.next = prev;
23             prev = curr;
24             curr = next;
25         }
26         return prev;
27     }
28 //递归
29     public static ListNode Recursion(ListNode head){
30         if (head == null || head.next == null){
31             return head;
32         }
33         ListNode new_head = Recursion(head.next);
34         head.next.next = head;
35         head.next = null;
36         return new_head;
37     }
38 
39     public static void main(String[] args) {
40         ListNode node5 = new ListNode(5, null);
41         ListNode node4 = new ListNode(4, node5);
42         ListNode node3 = new ListNode(3, node4);
43         ListNode node2 = new ListNode(2, node3);
44         ListNode node1 = new ListNode(1, node2);
45 
46         iterats(node1);
47         ListNode prev = Recursion(node1);
48         System.out.println(prev);
49     }
50 }

 

posted on 2022-09-21 17:23  一枚努力学习的小白  阅读(15)  评论(0编辑  收藏  举报