【leetcode 206】反转链表

在这里插入图片描述
方法一:采用迭代

在这里插入图片描述

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode pre=null;
        ListNode curr=head;
        while(curr!=null){
            ListNode temp=curr.next;
            curr.next=pre;
            pre=curr;
            curr=temp;
        }
        return pre;
    }
}

完整的运行实例

public class maintest {
    public static void main(String[] args) {
 
        //创建链表list1,链表有2个结点
        ListNode list1 = new ListNode(1);
        list1.next=new ListNode(2);

        //遍历list1的链表
        ListNode temp1=list1;     //定义一个指针temp1指向list1头结点
        while(temp1!=null){
            System.out.println(temp1.val);
            temp1=temp1.next;
        }

        //遍历反转后的链表list2
        Solution s1=new Solution();
        ListNode list2=s1.reverseList(list1);  //返回list2的头结点
        ListNode temp2=list2;
        
        while(temp2!=null){
            System.out.println(temp2.val);
            temp2=temp2.next;
        }
    }
}

class ListNode {
    int val;
    ListNode next;
    ListNode(int x) { val = x; }
}

//注意java的函数都需要定义在一个类中
class Solution{
    public ListNode reverseList(ListNode head) {
        ListNode prev = null;
        ListNode curr = head;
        while (curr != null) {
            ListNode nextTemp = curr.next;
            curr.next = prev;
            prev = curr;
            curr = nextTemp;
        }
        return prev;
    }
}

在这里插入图片描述

方法二:采用递归
在这里插入图片描述

思路解析

注意:这里ListNode p始终返回的是新链表的结点

帮助理解1在这里插入图片描述
帮助理解2
在这里插入图片描述

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
        if ( head==null||head.next==null) return head;   //这句话用于判断如果链表本身就是空链表或者到了链表的最后一个结点
        ListNode p = reverseList(head.next);
        head.next.next=head;
        head.next=null;
        return p;
    }
}

在这里插入图片描述

参考链接
https://leetcode-cn.com/problems/reverse-linked-list/solution/fan-zhuan-lian-biao-by-leetcode/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Bug 挖掘机

支持洋子

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值