Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 4

DS ASSIGN.

No #3

MARIA SARFRAZ SHAIKH


21510102
SY CSE
S6
Develop a program to reverse a singly linked list.

#include<bits/stdc++.h>
#define maria main
#define emp emplace_back
#define int long long int
using namespace std;

class Node{
public:
    int data;
    Node* next;
    Node(int data){
        this->data=data;
        this->next=NULL;
    }
};
void print(Node* &head){
    Node* temp=head;
    while (temp!=NULL){
        cout<<temp->data<<" ";
        temp=temp->next;
    }
    cout<<endl;
}
void inathead(Node* &head,int data){
    Node* temp=new Node(data);
    temp->next=head;
    head=temp;
}
 void inattail(Node* &head,int data){
    Node* temp=head;
    while (temp->next!=NULL){
        temp=temp->next;
    }
    Node* ptr=new Node(data);
    temp->next=ptr;
    ptr->next=NULL;
}
void reversell(Node* &head){
    Node* f=head;
    Node* pre=NULL;
    Node* s;
    while(f!=NULL){
        s=f->next;
        f->next=pre;
        pre=f;
        f=s;
    }
    head=pre;
}

void inatpos(Node* &head, int pos,int d){


    if(pos==1){
        inathead(head,d);
        return;
    }
    Node* temp=head;
    int cnt=1;
    while(cnt<pos-1){
        temp=temp->next;
        cnt++;
    }
    Node* nti=new Node(d);
    nti->next=temp->next;
    temp->next=nti;
}

int32_t maria(){
    Node* node1=new Node(10);
    Node* head=node1;
    head=node1;
    inathead(head,15);//inserting at head
    inattail(head,18);//inserting at tail
    inatpos(head,3,424);//inserting at particular position
    cout<<"Original Linked List:-";
    print(head);
    cout<<"After reverse the Linked List become:-";
    reversell(head);//reversing the linked list
    print(head);
    cout<<endl;
    return 0;
}

Output:-

You might also like