In: Computer Science
How to reverse linked list below,thank you!
#include <stdlib.h>
#include <stdio.h>
struct list
{
int data;
struct list *next;
};
typedef struct list node;
typedef node *link;
int main()
{
link ptr,head;
int num,i;
head = ( link ) malloc(sizeof(node));
ptr = head;
printf("enter 10 data \n");
for ( i = 0; i <= 9; i++ )
{
scanf("%d",&num);
ptr->data = num;
ptr->next = ( link ) malloc(sizeof(node));
if ( i == 9 )
ptr->next = NULL;
else
ptr = ptr->next;
}
printf("original linked list\n");
ptr = head;
while ( ptr != NULL )
{
printf("data==> %d\n",ptr->data);
ptr = ptr->next;
}
system("pause");
return 0;
}
#include <stdlib.h>
#include <stdio.h>
struct list
{
int data;
struct list *next;
};
typedef struct list node;
typedef node *link;
list *reverseLinkedList (list *head)
{
if ( head == NULL)
{
return NULL;
}
list *temp = head;
list *curr = head;
list * pred = NULL;
while(curr != NULL)
{
temp = temp ->next;
curr->next = pred;
pred = curr;
curr = temp;
}
head = pred;
return head;
}
int main()
{
link ptr,head;
int num,i;
head = ( link ) malloc(sizeof(node));
ptr = head;
printf("enter 10 data \n");
for ( i = 0; i <= 9; i++ )
{
scanf("%d",&num);
ptr->data = num;
ptr->next = ( link ) malloc(sizeof(node));
if ( i == 9 )
ptr->next = NULL;
else
ptr = ptr->next;
}
printf("original linked list\n");
ptr = head;
while ( ptr != NULL )
{
printf("data==> %d\n",ptr->data);
ptr = ptr->next;
}
head = reverseLinkedList(head);
printf("reverse linked list\n");
ptr = head;
while ( ptr != NULL )
{
printf("data==> %d\n",ptr->data);
ptr = ptr->next;
}
system("pause");
return 0;
}