Java单链表递归逆置

  • Post author:
  • Post category: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;
	}
}



版权声明:本文为weixin_43732535原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。