用java写出反转链表
以下是Java代码实现反转链表:
public class ReverseLinkedList {
public static void main(String[] args) {
// 创建链表
ListNode head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(3);
head.next.next.next = new ListNode(4);
System.out.println("原链表:");
printLinkedList(head);
// 反转链表
ListNode newHead = reverseLinkedList(head);
System.out.println("反转后的链表:");
printLinkedList(newHead);
}
/**
* 反转链表
* @param head 原链表头结点
* @return 反转后的链表头结点
*/
public static ListNode reverseLinkedList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode newHead = reverseLinkedList(head.next);
head.next.next = head;
head.next = null;
return newHead;
}
/**
* 输出链表
* @param head 链表头结点
*/
public static void printLinkedList(ListNode head) {
ListNode node = head;
while (node != null) {
System.out.print(node.val + " ");
node = node.next;
}
System.out.println();
}
}
class ListNode {
int val;
ListNode next;
ListNode(int val) {
this.val = val;
}
}
其中,reverseLinkedList方法使用递归实现链表反转,递归到链表末尾后逐层返回,将当前节点的next节点的next指向当前节点,然后将当前节点的next指向null,最后返回反转后的链表头结点。printLinkedList方法用于输出链表元素。
原文地址: http://www.cveoy.top/t/topic/bnoJ 著作权归作者所有。请勿转载和采集!