mercredi 22 juillet 2020

Problem In Deleting the first node of a Singely Linked List

I am trying to delete the first node of the singely linked list. But i am getting some random output when i traverse through the Linked List. Here is the code:

#include <iostream>
#include<bits/stdc++.h> 
#define ll long long int
using namespace std;

struct node{
  ll data;
  node *next;
};
class sll{
 private: node *head,*tail; ll len;     
 public:
    sll(){
        head=NULL;
        tail=NULL;
        len=0;
    }
    void push(ll n){
        node *temp=new node;
        temp->data=n;
        temp->next=NULL;
        if(head==NULL){
            head=temp;
            tail=temp;
        }   
        else{
            tail->next = temp;
            tail=temp;          
        }
        len++;
    }
    void show(){
        node *temp=new node;
        temp=head;
        while(temp!=NULL){
            cout<<temp->data<<" ";
            temp=temp->next;
        }
        cout<<"\n";
    }

    void pop(ll pos){
        if(pos==1){
            node *temp=new node;
            temp=head;
            head=head->next;
            delete(temp);
            
        }
        if(pos==len){
            ll i=1;
            node *temp=new node;
            temp=head;
            while(i<len-1){
                temp=temp->next;
                i++;
            }
        
            node *p=tail;
            tail=temp;
            temp->next=NULL;
            delete(p);
            
        }
        else{
            ll i=1;
            node *temp=head;
            while(i<pos-1){
                temp=temp->next;
                i++;
            }
            node *p;
            p=temp->next;
            temp->next=p->next;
            delete(p);
        }
        len--;
    }

  };


int main(){
 sll a;
 a.push(1);
 a.push(2);
 a.push(3);
 a.push(4);
 a.show();
 a.pop(1);
 a.show();
//a.show();

}

Here i have created a class called sll that has basic function push() for pushing the numbers in the linked list at the end. There is a function show() which iterates from the first element stored in head node till the tail node. The output that is expected at the end is :

2 3 4 

But instead I get the output:

2 4

Please tell me where am I going wrong.

Aucun commentaire:

Enregistrer un commentaire