Take the given starter code listed with this assignment and

 Take the given starter code listed with this assignment and add in the code needed to reverse the linked list. Your algorithm should complete in linear time and should not require you to build a second list.    #include <stdio.h> #include <stdlib.h>  struct node; typedef struct node Node;  struct node {         int data;         Node* next; };  //declare your function here.   int main(int argc, char* argv[]) {         Node* head = NULL;         int i;         Node* temp;          //set up a test list with values 9->8->7->...->0         for (i = 0; i < 10; i++)         {                 temp = (Node*)malloc(sizeof(Node));                 if (temp == NULL)                 {                         printf(\"out of memory?\ \");                         exit(1);                 }                 temp->data = i;                 temp->next = head;                 head = temp;         }          //call your function to reverse the list (should work for any list given the head node).           //print the reversed list.         temp = head;         while (temp != NULL)         {                 printf(\"%d\ \", temp->data);                 temp = temp->next;         }          return 0; }  //Define your function here 

Solution

#include <stdio.h>
#include <stdlib.h>

struct node;
typedef struct node Node;

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

//declare your function here.
void reverse(Node* );

int main(int argc, char* argv[])
{
Node* head = NULL;
int i;
Node* temp;

//set up a test list with values 9->8->7->...->0
for (i = 0; i < 10; i++)
{
temp = (Node*)malloc(sizeof(Node));
if (temp == NULL)
{
printf(\"out of memory?\ \");
exit(1);
}
temp->data = i;
temp->next = head;
head = temp;
}

//call your function to reverse the list (should work for any list given the head node).
       reverse(head);

//print the reversed list.
temp = head;
while (temp != NULL)
{
printf(\"%d\ \", temp->data);
temp = temp->next;
}

return 0;
}

//Define your function here
void reverse(Node* head)
{
Node* prev = NULL;
Node* cur = head;
Node* next;
while (current != NULL)
{
next = cur->next;
cur->next = prev;   
prev = cur;
cur = next;
}
head = prev;
}  

 Take the given starter code listed with this assignment and add in the code needed to reverse the linked list. Your algorithm should complete in linear time an
 Take the given starter code listed with this assignment and add in the code needed to reverse the linked list. Your algorithm should complete in linear time an

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site