Reversing a linked list

前端 未结 5 1060
萌比男神i
萌比男神i 2021-01-17 06:48

Problem in Reversing a linked list without using recursion.

I used this method, but when i try and run this back home, I am not able to print the reverse of the lin

5条回答
  •  遇见更好的自我
    2021-01-17 07:15

    class Node {
        Node next;
        int value;
    
        public Node() {
        }
    
        public Node(Node next, int value) {
            super();
            this.next = next;
            this.value = value;
        }
    
        public Node getNext() {
            return next;
        }
    
        public void setNext(Node next) {
            this.next = next;
        }
    
        public int getValue() {
            return value;
        }
    
        public void setValue(int value) {
            this.value = value;
        }
    
    }
    
    public class Linkedlist {
        private Node head = null;
    
        public Linkedlist(Node head) {
            this.head = head;
        }
    
        public void iterate() {
            Node current = head;
            while (current != null) {
                System.out.println(current.getValue());
                current = current.getNext();
            }
        }
    
        public void reverse() {
            Node current = head;
            Node prev = null;
            while (current != null) {
                Node temp = current.next;
                current.next = prev;
                prev = current;
                current = temp;
            }
            head = prev;
        }
    
        public static void main(String[] args) {
            Node n = new Node(null, 10);
            Node n1 = new Node(n, 20);
            Node n2 = new Node(n1, 30);
            Node n3 = new Node(n2, 40);
            Node n4 = new Node(n3, 50);
            Node n5 = new Node(n4, 60);
            Linkedlist linkedlist = new Linkedlist(n5);
            linkedlist.iterate();
            linkedlist.reverse();
            System.out.println("------------------REVERSED---------------------");
            linkedlist.iterate();
    
        }
    }
    

提交回复
热议问题