0% found this document useful (0 votes)
3 views

Dsa Lab Assignment 2 Hira[1]

Uploaded by

Abdur Rehman
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Dsa Lab Assignment 2 Hira[1]

Uploaded by

Abdur Rehman
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 5

DATA STRUCTURES LAB

ASSIGNMENT NO 2

SUBMITTED BY: HIRA ATIF (421)


SUBMITTED TO: MISS IQRA
KHALIL
Palindrome Linked List
Palindrome function:

bool isPalindrome()
{
if (head == nullptr || head->next == nullptr)
{
return true;
}

Node *slow = head;


Node *fast = head;
while (fast != nullptr && fast->next != nullptr)
{
slow = slow->next;
fast = fast->next->next;
}

Node *secondHalf = reverse(slow);


Node *tempSecondHalf = secondHalf;

Node *firstHalf = head;


bool isPalin = true;
while (secondHalf != nullptr)
{
if (firstHalf->data != secondHalf->data)
{
isPalin = false;
break;
}
firstHalf = firstHalf->next;
secondHalf = secondHalf->next;
}
reverse(tempSecondHalf);
return isPalin;
}
Implementing stack using link list.
#include <iostream>
using namespace std;

class node
{
private:
int data;
node *next;

public:
node(int value)
{
data = value;
next = nullptr;
}
};

class stack
{
private:
node *top;

public:
stack()
{
top = nullptr;
}

void push(int value)


{
node *newNode = new node(value);
newNode->next = top;
top = newNode;
cout << value << " pushed into the stack. " << endl;
}

void Pop() {
if (top == nullptr) {
cout << "The stack is empty!" << endl;
return;
}
Node* temp = top;
cout << top->data << " popped from the stack." << endl;
top = top->next;
delete temp;
}

int Top() {
if (top == nullptr) {
cout << "The stack is empty!" << endl;
return -1;
}
return top->data;
}

bool Empty() {
return top == nullptr;
}

};

int main() {
Stack s1;

int choice, value;

while (true) {
cout << "\nMenu:" << endl;
cout << "1. Push" << endl;
cout << "2. Pop" << endl;
cout << "3. View Top Element" << endl;
cout << "4. Check if Stack is Empty" << endl;
cout << "5. Exit" << endl;
cout << "Enter your choice: ";
cin >> choice;

switch (choice) {
case 1:
cout << "Enter the value to push: ";
cin >> value;
s1.Push(value);
break;
case 2:
s1.Pop();
break;
case 3:
value = s1.Top();
if (value != -1) {
cout << "Top element: " << value << endl;
}
break;
case 4:
if (s1.Empty()) {
cout << "The stack is empty." << endl;
} else {
cout << "The stack is not empty." << endl;
}
break;
case 5:
cout << "Exiting..." << endl;
return 0;
default:
cout << "Invalid choice! Please try again." << endl;
}
}

return 0;
}
};

You might also like