Java单链表递归逆置

题目链接:https://leetcode.cn/problems/UHnkqh/description/

核心代码

方法一:有返回值的递归

class Solution {
    public ListNode reverseList(ListNode head) {
        return recur(head, null);    // 调用递归并返回
    }
    private ListNode recur(ListNode cur, ListNode pre) {
        if (cur == null) return pre; // 终止条件
        ListNode res = recur(cur.next, cur);  // 递归后继节点
        cur.next = pre;              // 修改节点引用指向
        return res;                  // 返回反转链表的头节点
    }
}

方法二:

public static void ReverseNode(Node node,Node pre){

		if(node==null) return;
		Node next=node.next;
		node.next=pre;
		ReverseNode(next,node);
	}

主程序


public class Reverse{


	public static void ReverseNode(Node node,Node pre){

		if(node==null) return;
		Node next=node.next;
		node.next=pre;
		ReverseNode(next,node);
	}
	static void Print(Node node){
		System.out.println(node.val);
		if(node.next!=null)
			Print(node.next);
	}
	public static void main(String[]args){

		Node q1=new Node(1);
		Node q2=new Node(2);
		Node q3=new Node(3);
		Node q4=new Node(4);
		Node q5=new Node(5);
		q1.next=q2;
		q2.next=q3;
		q3.next=q4;
		q4.next=q5;

		ReverseNode(q1,null);
		Print(q5);
		
		
	}
}

类定义

public class Node{

	int val;
	Node next;
	Node(int val){
		this.val=val;
	}
	Node(){}
	Node(int val,Node next){
		this.val=val;
		this.next=next;
	}
	public void setNext(Node next){
		this.next=next;
	}
	Node getNext(){
		return next;
	}
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值