Uploaded by Tiahna Padilla

CS400Re-arrangeLinkedList

advertisement
// CS400Re-arrangeLinkedList.cpp //T347C453_ TiahnaPadilla
#include <iostream>
struct Node {
int data;
struct Node* next;
};
typedef Node* NodePtr;
// Function to create a new node with the given data
NodePtr createNode(int data) {
NodePtr temp = new Node;
temp->data = data;
temp->next = NULL;
return temp;
}
// Function to print the linked list
void printList(NodePtr head) {
while (head != NULL) { std::cout << head->data << " "; head = head->next; } }
void rearrangeLinkedList(NodePtr& head) {
//TODO:
}
// test your solution:
int main() {
// Create the linked list: 1 -> 2 -> 5 -> 8 -> 3 -> 6 -> 7 -> 4
NodePtr head = createNode(1);
head->next = createNode(2);
head->next->next = createNode(5);
head->next->next->next = createNode(8);
head->next->next->next->next = createNode(3);
head->next->next->next->next->next = createNode(6);
head->next->next->next->next->next->next = createNode(7);
head->next->next->next->next->next->next->next = createNode(4);
// Print the original list
std::cout << "Original List: ";
printList(head);
// Re-arrange the list
rearrangeLinkedList(head);
// Print the re-arranged list
std::cout << "Re-arranged List: ";
printList(head);
// Clean up the memory
NodePtr current = head;
while (current != nullptr) {
NodePtr temp = current;
current = current->next;
delete temp;
}
return 0;
}
Download