Sort by

recency

|

913 Discussions

|

  • + 0 comments

    Great approach! Reversing a singly linked list by inserting nodes at the beginning of a new list is efficient and clean. This function is especially useful in coding interviews and beginner data structure practice.

    Also, if anyone is looking for a peaceful break from coding or wants to learn to read the Quran online, I invite you to visit my website: 👉 Zeenat ul Quran – Online Quran Learning Platform

    It’s a great resource for all ages to learn Quran, namaz, and Islamic basics from home. 😊

  • + 0 comments

    My python solution :

    def reverse(llist):
        llist_2 = SinglyLinkedList()
        current = llist
        while current :
            node = SinglyLinkedListNode(current.data)
            node.next = llist_2.head
            llist_2.head = node
            current = current.next
        return llist_2.head
    
  • + 0 comments

    My Java solution:

    public static SinglyLinkedListNode reverse(SinglyLinkedListNode llist) {
            SinglyLinkedListNode reverseList = null;
            SinglyLinkedListNode current = llist;
            
            while (current != null) {
                SinglyLinkedListNode temp = new SinglyLinkedListNode(current.data);
                temp.next = reverseList;
                reverseList = temp;
                current = current.next;
            }
            
            return reverseList;
        }
    
  • + 0 comments

    My Java solution with o(n) time complexity and o(1) space complexity:

    public static SinglyLinkedListNode reverse(SinglyLinkedListNode llist) { if(llist == null) return null; if(llist.next == null) return llist;

        SinglyLinkedListNode curr = llist;
        SinglyLinkedListNode prev = null;
        SinglyLinkedListNode temp = null; 
    
        while(curr != null){
            temp = curr.next;
            //point curr node to prev
            curr.next = prev;
            //set prev = curr node
            prev = curr;
            curr = temp;
        }
    
        return prev;
    }
    
  • + 0 comments
    public static SinglyLinkedListNode reverse(SinglyLinkedListNode llist) {
    

    if(llist == null) return null; if(llist.next == null) return llist;

        SinglyLinkedListNode curr = llist;
        SinglyLinkedListNode prev = null;
        SinglyLinkedListNode temp = null; 
    
        while(curr != null){
            temp = curr.next;
            //point curr node to prev
            curr.next = prev;
            //set prev = curr node
            prev = curr;
            curr = temp;
        }
    
        return prev;
    }