Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package ch.claude_martin;
- import java.util.Arrays;
- class SinglyLinkedList {
- private static class ListNode {
- int value;
- ListNode next;
- ListNode(int val) {
- value = val;
- next = null;
- }
- }
- private ListNode head;
- public SinglyLinkedList(ListNode head) {
- this.head = head;
- }
- /**
- * 1→2→3→4→5→␀
- */
- static SinglyLinkedList makeList(int... values) {
- ListNode head = null, prev = null;
- for (int v : values) {
- ListNode current = new ListNode(v);
- if (prev != null)
- prev.next = current;
- else head = current;
- prev = current;
- }
- return new SinglyLinkedList(head);
- }
- public void reverseList() {
- reverseListResursive(head, head);
- }
- private void reverseListResursive(final ListNode head, final ListNode node) {
- final ListNode next = node.next;
- if (next != null) {
- if (next.next == null) {
- head.next.next = next;
- head.next = node;
- }
- reverseListResursive(head, next);
- if (node != head && next.next != null)
- next.next = node;
- } else {
- final int value = node.value;
- node.value = head.value;
- head.value = value;
- }
- }
- public void printList() {
- printList(this.head);
- }
- static void printList(ListNode head) {
- if (head == null)
- System.out.println('␀');
- else {
- System.out.print(head.value);
- System.out.print('→');
- printList(head.next);
- }
- }
- }
- public class Solution {
- public static void main(String[] args) {
- SinglyLinkedList list = SinglyLinkedList.makeList(Arrays.stream(args).mapToInt(Integer::parseInt).toArray());
- list.printList();
- list.reverseList();
- list.printList();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement