In: Computer Science
In c++:
Code Challenge
Consider the following code:
struct ListNode { int value; struct ListNode *next; };
ListNode *head; // List head pointer
Assume that a linked list has been created and head points to the first node. Write code that traverses the list displaying the contents of each node’s value member
Now write the code that destroys the linked list
#include<iostream> using namespace std; struct ListNode { int value; struct ListNode *next; }; void printList(ListNode *head) { cout << "List is: "; while (head != NULL) { cout << head->value << " "; head = head->next; } cout << endl; } void destroyList(ListNode *head) { ListNode *p; while (head != NULL) { p = head->next; delete head; head = p; } } int main() { ListNode *head = new ListNode; head->value = 2; head->next = new ListNode; head->next->value = 8; head->next->next = new ListNode; head->next->next->value = 9; head->next->next->next = new ListNode; head->next->next->next->value = 4; head->next->next->next->next = NULL; printList(head); destroyList(head); return 0; }