1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
| class ListNode { int value; ListNode? next;
ListNode(this.value, [this.next]); }
ListNode? reverseLinkedListRecursive(ListNode? head) { if (head == null || head.next == null) { return head; }
ListNode? newHead = reverseLinkedListRecursive(head.next);
head.next?.next = head; head.next = null;
return newHead; }
void main() { ListNode node1 = ListNode(1); ListNode node2 = ListNode(2); ListNode node3 = ListNode(3); ListNode node4 = ListNode(4); ListNode node5 = ListNode(5);
node1.next = node2; node2.next = node3; node3.next = node4; node4.next = node5;
print("Original List:"); printList(node1);
ListNode? reversedHead = reverseLinkedListRecursive(node1);
print("Reversed List:"); printList(reversedHead); }
void printList(ListNode? head) { ListNode? current = head; while (current != null) { print(current.value); current = current.next; } }
|