Untitled

mail@pastecode.io avatar
unknown
c_cpp
a month ago
1.8 kB
3
Indexable
Never
#include<bits/stdc++.h>
using namespace std;
class Node{
    public:
        int data;
        Node* next;

        Node(int value){
            data = value;
            next = nullptr;
        }
        Node(int value, Node* valNext){
            data = value;
            next = valNext;
        }
};


Node* arrayToLL(vector<int> &arr){
    Node* head = new Node(arr[0]);
    Node* mover = head;

    // Node* mover = head;
    for(int i=1; i<arr.size(); i++){
        Node* temp = new Node(arr[i]);
        mover->next = temp;
        mover = temp;
    }

    return head;

}



Node* traverseLL(Node* head = nullptr){
    if(!head){
        cout<<"Plese Provide atleast one node!";
    }
    Node* temp = head;
    
    while(temp){
        cout<<temp->data<<" -> ";
        temp = temp->next;
        if(!temp){
            cout<<"NULL";
        }
    }
}

Node* removeNthNode(Node* head, int n){
    // if list is empty
    if(head == NULL) return head;

    // if n == 1 means only one node
    
    if(n == 1){
        Node* temp = head;
        head = head->next;
        delete temp;
        return head;
    }

    // if n==3 or 4 or 5 
    int count = 0;
    Node* temp = head;
    Node* prev = NULL;
    while(temp){
        count++;
        if(count == n){
            prev->next == prev->next->next;
            free(temp);
            cout<<n<<"yes"<<endl;
            return head;
        }
        prev = temp;
        temp = temp->next;
    }
    return head;

}

int main(){

    vector<int> arr = {1, 2, 3, 4, 5, 6, 7, 8, 9};
    Node* head = arrayToLL(arr);

    traverseLL(head);

    cout<<endl;

    Node* head2 = removeNthNode(head, 9);
    traverseLL(head2);

    return 0;
}
Leave a Comment