DSA Day 52/100

DSA Day 52/100

Topic: Linked List

Questions Successfully Completed: 1

1) Remove duplicate element from sorted Linked List

Easy

Remove duplicate element from sorted Linked List

Time Complexity : O(N)

Space Complexity : O(1)

Question
Input: LinkedList: 2->2->4->5 Output: 2 4 5 Explanation: In the given linked list 2 ->2 -> 4-> 5, only 2 occurs more than 1 time.
class DupNode{
    int data;
    DupNode next;
    public DupNode(int data){
        this.data = data;
        this.next = null;
    }
}
public class removeDuplicatedfromSortedLL {
    static void removeDuplicatesLL(DupNode start){

        // display the LL
        DupNode f = start;
        while(f!=null){
            System.out.print(f.data + " | ");
            f=f.next;
        }

        // remove duplicates
        DupNode q = start;
        DupNode p = q.next;

        while(p!=null){
            if(q.data==p.data){
                q.next = p.next;
                p = p.next;
            }
            else{
                p = p.next;
                q = q.next;
            }
        }

        System.out.println("\nLinked List after removing elements");
        f=start;
        while(f!=null){
            System.out.print(f.data + " | ");
            f=f.next;
        }



    }
    public static void main(String[] args) {
        DupNode a = new DupNode(2);
        DupNode b = new DupNode(2);
        DupNode c = new DupNode(3);
        DupNode d = new DupNode(3);
        DupNode e = new DupNode(4);

        DupNode head = a;
        a.next = b;
        b.next = c;
        c.next = d;
        d.next = e;
        e.next = null;

        removeDuplicatesLL(head);

    }
}

/*OUTPUT

2 | 2 | 3 | 3 | 4 |
Linked List after removing elements
2 | 3 | 4 |

* */

Thank you for reading :)