链表反转-JavaDG实现

对于链表的反转,用常规的迭代法,是很简单的,使用两个指针;对于用递归法,则是很经典题了,我就觉得对于递归方法和常用的迭代法,大家最好都熟悉掌握,不要刻意的去避免哪一点;

 1     • 链表反转
 2         ○ 常规的迭代实现:
 3                 public ListNode reverseList(ListNode head) {
 4                     if (head==null)
 5                         return head;
 6                     ListNode currentNode=head;
 7                     head=null;
 8                     while (currentNode!=null){
 9                         ListNode tempNode=currentNode.next;
10                         currentNode.next=head;
11                         head=currentNode;
12                         currentNode=tempNode;
13                     }
14                     return head;
15                 }
16         ○ 递归的实现,很经典的思想:
17                 public ListNode reverseListDG(ListNode head) {
18                     if (head==null||head.next==null)
19                         return head;
20                     ListNode newHead=reverseListDG(head.next);
21                     head.next.next=head;
22                     head.next=null;
23                     return newHead;
24                 }
25 
26     

 

posted @ 2023-04-05 22:05  Mexcellent  阅读(40)  评论(0)    收藏  举报