随笔 - 64  文章 - 0  评论 - 2  阅读 - 4485

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   一枚努力学习的小白  阅读(16)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
< 2025年3月 >
23 24 25 26 27 28 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 1 2 3 4 5

点击右上角即可分享
微信分享提示