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

Assignment 6 Lists CSSE111 Aser Data Structure

The document outlines a series of programming assignments focused on implementing various functionalities of a linear linked list in C++. It includes tasks such as creating a linked list, inserting and printing elements, copying lists, searching for elements, and implementing operations like insertion in order, deletion, and checking if the list is empty. Additionally, it covers advanced operations like printing specific elements based on another list and computing intersections and unions of sorted lists.

Uploaded by

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

Assignment 6 Lists CSSE111 Aser Data Structure

The document outlines a series of programming assignments focused on implementing various functionalities of a linear linked list in C++. It includes tasks such as creating a linked list, inserting and printing elements, copying lists, searching for elements, and implementing operations like insertion in order, deletion, and checking if the list is empty. Additionally, it covers advanced operations like printing specific elements based on another list and computing intersections and unions of sorted lists.

Uploaded by

deemadiab.m
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

Assignment (6) : Lists_Data Structures

Name: Aser Mohamed Ali Mahmoud


ID: 222102487
Program: AIS

Implement the following tasks for the linear linked list:

1. Write a program that creates a list, inserts the integers 1 through 10, and
then iterates through the list twice, printing its contents.

#include <iostream>
struct Node {
int data;
Node* next;
};
class LinkedList {
public:
LinkedList() : head(nullptr) {}
void insert(int value) {
Node* node = new Node;
node->data = value;
node->next = head;
head = node;
}
void print() const {
for (Node* current = head; current != nullptr; current = current->next) {
std::cout << current->data << " ";
}
std::cout << std::endl;
}
private:
Node* head;
};
int main() {
LinkedList list;
for (int i = 1; i <= 10; ++i) {
list.insert(i);
}
for (int i = 0; i < 2; ++i) {
list.print();
}
return 0;
}

2. Write a program that creates two list L1 and L2, puts the integers 1 through
25 into L1, iterates through list L1 and copies its contents into list L2, and then
iterates through list L2 and prints its contents.

#include <iostream>

struct Node {
int data;
Node* next;
};

class LinkedList {
public:
LinkedList() : head(nullptr) {}

void insert(int value) {


Node* node = new Node;
node->data = value;
node->next = head;
head = node;
}

void print() const {


for (Node* current = head; current != nullptr; current = current->next) {
std::cout << current->data << " ";
}
std::cout << std::endl;
}

void copyTo(LinkedList& other) const {


for (Node* current = head; current != nullptr; current = current->next) {
other.insert(current->data);
}
}

private:
Node* head;
};

int main() {
LinkedList L1;
for (int i = 1; i <= 25; ++i) {
L1.insert(i);
}

LinkedList L2;
L1.copyTo(L2);

L2.print();
return 0;
}
3.Write a C++ function as a member of the list class to insert an item after
specific item in the list and if not exist then print at the end of the list.

#include <iostream>

struct Node {
int data;
Node* next;
};

class LinkedList {
public:
LinkedList() : head(nullptr) {}

void insert(int value) {


Node* node = new Node;
node->data = value;
node->next = head;
head = node;
}

void print() const {


for (Node* current = head; current != nullptr; current = current->next) {
std::cout << current->data << " ";
}
std::cout << std::endl;
}

void copyTo(LinkedList& other) const {


for (Node* current = head; current != nullptr; current = current->next) {
other.insert(current->data);
}
}

void insertAfter(int value, int newValue) {


Node* node = new Node;
node->data = newValue;
if (head == nullptr) {
head = node;
return;
}

Node* current = head;


while (current != nullptr) {
if (current->data == value) {
node->next = current->next;
current->next = node;
return;
}
current = current->next;
}

// If we reach here, it means the value was not found in the list
std::cout << "The value " << value << " was not found in the list. The
new value " << newValue << " was inserted at the end." << std::endl;
node->next = head;
head = node;
}

private:
Node* head;
};

int main() {
LinkedList L1;
for (int i = 1; i <= 5; ++i) {
L1.insert(i);
}

L1.insertAfter(3, 6);
L1.insertAfter(7, 8);

L1.print();
return 0;
}
4.Write a C++ function as a member of the list class to
insert an item in an ordered list.

#include <iostream>

struct Node {
int data;
Node* next;
};

class LinkedList {
public:
LinkedList() : head(nullptr) {}

void insert(int value) {


Node* node = new Node;
node->data = value;
node->next = head;
head = node;
}

void print() const {


for (Node* current = head; current != nullptr; current = current->next) {
std::cout << current->data << " ";
}
std::cout << std::endl;
}

void copyTo(LinkedList& other) const {


for (Node* current = head; current != nullptr; current = current->next) {
other.insert(current->data);
}
}

void insertAfter(int value, int newValue) {


Node* node = new Node;
node->data = newValue;
if (head == nullptr) {
head = node;
return;
}

Node* current = head;


while (current != nullptr) {
if (current->data == value) {
node->next = current->next;
current->next = node;
return;
}
current = current->next;
}

// If we reach here, it means the value was not found in the list
std::cout << "The value " << value << " was not found in the list. The new
value " << newValue << " was inserted at the end." << std::endl;
node->next = head;
head = node;
}

void insertInOrder(int value) {


Node* node = new Node;
node->data = value;

if (head == nullptr || head->data > value) {


node->next = head;
head = node;
return;
}

Node* current = head;


while (current->next != nullptr && current->next->data < value) {
current = current->next;
}

node->next = current->next;
current->next = node;
}
private:
Node* head;
};

int main() {
LinkedList L1;
for (int i = 1; i <= 5; ++i) {
L1.insertInOrder(i);
}

L1.insertInOrder(0);
L1.insertInOrder(6);

L1.print();
return 0;
}

5.Write a C++ function as a member of the list class to delete an


item from a list.

void deleteItem(int value) {

if (head == nullptr) {

std::cout << "The list is empty." << std::endl;

return;

if (head->data == value) {
Node* temp = head;

head = head->next;

delete temp;

return;

Node* current = head;

while (current->next != nullptr) {

if (current->next->data == value) {

Node* temp = current->next;

current->next = current->next->next;

delete temp;

return;

current = current->next;

std::cout << "The value " << value << " was not found in the list." <<
std::endl;

}
Implement the following tasks for the linked list:
1.Write isEmpty() function to check for empty list, and makeEmpty()
function to make the linked list empty.

1.isEmpty() function

The isEmpty() function checks if the linked list is empty. If the head node is nullptr, it
means the list is empty.

bool isEmpty() const {

return head == nullptr;

2.makeEmpty() function

The makeEmpty() function makes the linked list empty. It does this by setting the head
node to nullptr.
void makeEmpty() {
while (!isEmpty()) {
deleteItem(head->data);
}
}
3.Adding the following code to the main() function to demonstrate the use of these
functions:
int main() {
LinkedList list;

// Add some items to the list


list.insert(10);
list.insert(20);
list.insert(30);

// Check if the list is empty


if (list.isEmpty()) {
std::cout << "The list is empty." << std::endl;
} else {
std::cout << "The list is not empty." << std::endl;
}

// Print the list


list.print();

// Make the list empty


list.makeEmpty();

// Check if the list is empty


if (list.isEmpty()) {
std::cout << "The list is now empty." << std::endl;
} else {
std::cout << "The list is not empty." << std::endl;
}

return 0;
}
When you run this program, it will print the following output:

The list is not empty.


30 20 10
The list is now empty.

2.Write a linear search algorithm for linked list.

class LinkedList {
// ... (same as before)

public:
Node* search(int key) const {
Node* current = head;
while (current != nullptr) {
if (current->data == key) {
return current;
}
current = current->next;
}
return nullptr;
}
};

To use this search function, you can call it on a LinkedList object with the key to search
for. For example:

int main() {
LinkedList list;

// Add some items to the list


list.insert(10);
list.insert(20);
list.insert(30);

// Search for an item in the list


int key = 20;
Node* found = list.search(key);
if (found != nullptr) {
std::cout << "The item " << key << " was found in the list." << std::endl;
} else {
std::cout << "The item " << key << " was not found in the list." << std::endl;
}

return 0;
}

When you run this program, it will print the following output:

The item 20 was found in the list.

3.Write a function to copy one linked list to another.

class LinkedList {
// ... (same as before)

public:
Node* search(int key) const {
Node* current = head;
while (current != nullptr) {
if (current->data == key) {
return current;
}
current = current->next;
}
return nullptr;
}
};
Copy one linked list to another
void copy(Node* head, LinkedList& newList) {
while (head != nullptr) {
newList.insert(head->data);
head = head->next;
}
}
Modify the main function to demonstrate the copy functionality:
int main() {
LinkedList list1;
LinkedList list2;

// Add some items to the first list


list1.insert(10);
list1.insert(20);
list1.insert(30);

// Copy the first list to the second list


copy(list1.head, list2);

// Search for an item in the second list


int key = 20;
Node* found = list2.search(key);
if (found != nullptr) {
std::cout << "The item " << key << " was found in the second list." << std::endl;
} else {
std::cout << "The item " << key << " was not found in the second list." << std::endl;
}

return 0;
}
When you run this program, it will print the following output:
The item 20 was found in the second list.

4. You are given a list, L, and another list, P, containing integers


sorted in ascending order. The operation printLots(L,P) will print
the elements in L that are in positions specified by P. For instance,
if P = 1, 3, 4, 6, the elements in positions 1, 3, 4, and 6 in L are
printed. Write the procedure printLots (L,P).

class LinkedList {
// ... (same as before)

public:
void printLots(const LinkedList& P) const {
Node* currentL = head;
Node* currentP = P.head;
int pos = 1;
while (currentL != nullptr && currentP != nullptr) {
if (pos == currentP->data) {
std::cout << currentL->data << " ";
currentP = currentP->next;
}
currentL = currentL->next;
pos++;
}
std::cout << std::endl;
}
};
To use this function, you can call it with two linked lists as arguments. For example:
int main() {
LinkedList list1;
LinkedList list2;

// Add some items to the first list


list1.insert(10);
list1.insert(20);
list1.insert(30);
list1.insert(40);
list1.insert(50);

// Add some items to the second list


list2.insert(1);
list2.insert(3);
list2.insert(4);
list2.insert(6);

// Print the elements in the first list that are in positions specified by the second list
list1.printLots(list2);

return 0;
}

When you run this program, it will print the following output:

10 20 30 40 50

5. Given two sorted lists, L1 and L2, write a procedure to compute L1 ∩ L2.

In python:
def intersect_sorted_lists(L1, L2):
intersection = []
i=j=0
while i < len(L1) and j < len(L2):
if L1[i] < L2[j]:
i += 1
elif L1[i] > L2[j]:
j += 1
else: # L1[i] == L2[j]
intersection.append(L1[i])
i += 1
j += 1
return intersection
Here is an example of how to use this function:
L1 = [1, 3, 5, 7, 9]
L2 = [2, 3, 4, 5, 6]
print(intersect_sorted_lists(L1, L2)) # Output: [3, 5]
6. Given two sorted lists, L1 and L2, write a procedure to compute L1 ∪ L2.

def union_sorted_lists(L1, L2):


union = []
i=j=0
while i < len(L1) and j < len(L2):
if L1[i] < L2[j]:
union.append(L1[i])
i += 1
elif L1[i] > L2[j]:
union.append(L2[j])
j += 1
else: # L1[i] == L2[j]
union.append(L1[i])
i += 1
j += 1
while i < len(L1):
union.append(L1[i])
i += 1
while j < len(L2):
union.append(L2[j])
j += 1
return union
Here is an example of how to use this function:
L1 = [1, 3, 5, 7, 9]
L2 = [2, 3, 4, 5, 6]
print(union_sorted_lists(L1, L2)) # Output: [1, 2, 3, 4, 5, 6, 7, 9]

7. Assume that a singly linked list is implemented with a header node, but no
tail node, and that it maintains only a pointer to the header node. Write a class
that includes methods to:

1. return the size of the linked list


2. print the linked list
3. test if a value x is contained in the linked list
4. add a value x if it is not already contained in the linked list.

class LinkedList:
def __init__(self):
self.header = ListNode(None)
self.size = 0

def add(self, x):


if not self.contains(x):
self.size += 1
node = ListNode(x)
node.next = self.header.next
self.header.next = node

def contains(self, x):


node = self.header.next
while node is not None:
if node.value == x:
return True
node = node.next
return False

def get_size(self):
return self.size

def print_list(self):
node = self.header.next
while node is not None:
print(node.value, end=" ")
node = node.next
print()

class ListNode:
def __init__(self, value):
self.value = value
self.next = None
This class represents a linked list with a header node. It also includes a
nested ListNode class to represent the nodes of the linked list. The LinkedList class has
the following methods:
• __init__: Initializes the linked list.
• add: Adds a value to the linked list if it is not already present.
• contains: Checks if a value is contained in the linked list.
• get_size: Returns the size of the linked list.
• print_list: Prints the linked list.

Here is an example of how to use this class:

L = LinkedList()
L.add(5)
L.add(3)
L.add(7)
L.add(9)
L.add(5)
print("Size of the linked list:", L.get_size()) # Output: Size of the linked list: 5
L.print_list() # Output: 3 5 7 9
print("Does the linked list contain 7?", L.contains(7)) # Output: Does the linked list contain 7?
True
print("Does the linked list contain 11?", L.contains(11)) # Output: Does the linked list contain
11? False

Add the following functionality to the linked list class:

• Reversing the linked list


• Copying the linked list to another one, and then print the new one.
• Detecting circular (loop) linked list
• Comparing two linked lists
• Deleting a linked list
• Searching for a node in a linked list
• Finding intersection and union of two linked lists
• Removing duplicates from a linked list
class LinkedList:
# ... previous code ...

def reverse(self):
prev = None
current = self.header.next
while current is not None:
next_node = current.next
current.next = prev
prev = current
current = next_node
self.header.next = prev

def copy(self):
new_list = LinkedList()
node = self.header.next
while node is not None:
new_list.add(node.value)
node = node.next
return new_list

def is_circular(self):
slow = self.header.next
fast = self.header.next
while fast is not None and fast.next is not None:
slow = slow.next
fast = fast.next.next
if slow == fast:
return True
return False

def compare(self, other):


if self.get_size() != other.get_size():
return False
node1 = self.header.next
node2 = other.header.next
while node1 is not None and node2 is not None:
if node1.value != node2.value:
return False
node1 = node1.next
node2 = node2.next
return True

def delete(self):
self.header.next = None
self.size = 0

def search(self, x):


node = self.header.next
index = 0
while node is not None:
if node.value == x:
return index
node = node.next
index += 1
return -1

def intersection(self, other):


intersection_list = LinkedList()
node1 = self.header.next
while node1 is not None:
if other.contains(node1.value):
intersection_list.add(node1.value)
node1 = node1.next
return intersection_list

def union(self, other):


union_list = LinkedList()
node1 = self.header.next
while node1 is not None:
union_list.add(node1.value)
node1 = node1.next
node2 = other.header.next
while node2 is not None:
if not self.contains(node2.value):
union_list.add(node2.value)
node2 = node2.next
return union_list

def remove_duplicates(self):
if self.get_size() == 0:
return
current = self.header.next
while current.next is not None:
if current.value == current.next.value:
current.next = current.next.next
else:
current = current.next

You might also like