Reversing a linked list

前端 未结 5 1008
萌比男神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:21

    The corrected Code for reversing a Linked list without recursion.

    class Link {
    
        int data;
        public Link nextLink;
    
        Link(int d1) {
            data = d1;
        }
    }
    
    class List {
    
        Link head;
        Link revhead;
    
        List() {
            head = null;
        }
    
        boolean isEmpty(Link head) {
            return head == null;
        }
    
        void insert(int d1) {
            Link tempLink = new Link(d1);
            tempLink.nextLink = head;
            head = tempLink;
        }
    
        void printlist() {
            Link head1 = head;
            while (!isEmpty(head1)) {
                System.out.print(head1.data + " ");
                head1 = head1.nextLink;
            }
            System.out.println();
        }
    
        void reverse() {
            Link previous = null, temp = null;
            while (!isEmpty(head)) {
                temp = head.nextLink;
                head.nextLink = previous;
                previous = head;
                head = temp;
            }
    
            head = previous;
        }
    }
    
    public class Main {
    
        public static void main(String[] args) {
    
            List list1 = new List();
    
            list1.insert(10);
            list1.insert(20);
            list1.insert(30);
            list1.insert(40);
            list1.insert(50);
            list1.printlist();
            list1.reverse();
            list1.printlist();
        }
    }
    

提交回复
热议问题