反转单链表是一个常见的编程问题,可以使用迭代或递归的方式来实现。下面分别给出这两种方式的Java代码实现:
使用迭代方式实现反转单链表:
class ListNode {
int val;
ListNode next;
ListNode(int val) {
this.val = val;
this.next = null;
}
}
public class ReverseLinkedList {
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;
}
public static void main(String[] args) {
// 创建链表 1 -> 2 -> 3 -> 4 -> 5
ListNode head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(3);
head.next.next.next = new ListNode(4);
head.next.next.next.next = new ListNode(5);
// 创建 ReverseLinkedList 对象
ReverseLinkedList reverseLinkedList = new ReverseLinkedList();
// 反转链表
ListNode reversedHead = reverseLinkedList.reverseList(head);
// 输出反转后的链表 5 -> 4 -> 3 -> 2 -> 1
while (reversedHead != null) {
System.out.print(reversedHead.val + " ");
reversedHead = reversedHead.next;
}
}
}
使用递归方式实现反转单链表:文章来源:https://www.toymoban.com/news/detail-612370.html
class ListNode {
int val;
ListNode next;
ListNode(int val) {
this.val = val;
this.next = null;
}
}
public class ReverseLinkedList {
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode newHead = reverseList(head.next);
head.next.next = head;
head.next = null;
return newHead;
}
public static void main(String[] args) {
// 创建链表 1 -> 2 -> 3 -> 4 -> 5
ListNode head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(3);
head.next.next.next = new ListNode(4);
head.next.next.next.next = new ListNode(5);
// 创建 ReverseLinkedList 对象
ReverseLinkedList reverseLinkedList = new ReverseLinkedList();
// 反转链表
ListNode reversedHead = reverseLinkedList.reverseList(head);
// 输出反转后的链表 5 -> 4 -> 3 -> 2 -> 1
while (reversedHead != null) {
System.out.print(reversedHead.val + " ");
reversedHead = reversedHead.next;
}
}
}
无论是迭代还是递归,反转单链表的思路都是将当前节点的指针指向前一个节点,从而实现链表的反转。以上两种方式都可以正确实现单链表的反转。文章来源地址https://www.toymoban.com/news/detail-612370.html
到了这里,关于Java实现反转单链表的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!