力扣简206 反转链表

链表 递归 迭代

我现在认为迭代是每一步处理一个问题,形成一个比原来规模小但是处理方法相同的子问题,直至处理完。

看了下发现链表和树里的迭代 都用while做结束条件 整体放在一个大循环体内 一步一步处理 我下面列的这个方法应该也是迭代

 

自己做的就常规想法:直接取下来头,依次前插。

package leetcode01;
/*给你单链表的头节点 head,请你反转链表,并返回反转后的链表。*/
public class Solution206 {
    public static ListNode reverseList(ListNode head) {
        ListNode  res=null;
        ListNode  flag=res;
        while(head!=null) {
            res=head;
            head=head.next;
            res.next=flag;
            flag=res;
        }
        return res;
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        ListNode head=new ListNode(1,new ListNode(2,new ListNode(3)));
        System.out.println(reverseList(head));
    }

}

 

题解一:迭代 看了思路自己写的

public static ListNode reverseList(ListNode head) {
        ListNode pre=null;
        ListNode now=null;
        while(head!=null) {
            now=head;
            head=head.next;
            now.next=pre;
            pre=now;
        }
        return now;
    }

 

题解二:递归 看了思路自己写的 刚开始一直bug 然后又不停改改改 改了快要45分钟

 

 

 1 public static ListNode reverseList(ListNode head) {
 2         return reverse(head);
 3     }
 4     
 5     public static ListNode reverse(ListNode head) {
 6         ListNode temp=null;
 7         if(head!=null) { //不加这句找.next会指针溢出
 8             if(head.next!=null) {
 9                 temp = reverse(head.next);
10 //                temp.next=head;  //本来下面的head.next.next=head;用的是这句,但是这句中head是返回的结果的头,不是最后一个节点。这样会始终只有两个节点。
11                 head.next.next=head;
12                 head.next=null;
13             }    
14             else if(head.next==null)
15                 return head;
16         }    
17         return temp;    
18     }

 

posted @ 2022-05-30 13:10  Ssshiny  阅读(26)  评论(0)    收藏  举报