赞
踩
反转单链表是一个常见的编程问题,可以使用迭代或递归的方式来实现。下面分别给出这两种方式的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; } } }
使用递归方式实现反转单链表:
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; } } }
无论是迭代还是递归,反转单链表的思路都是将当前节点的指针指向前一个节点,从而实现链表的反转。以上两种方式都可以正确实现单链表的反转。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。