(optional question) Reverse linked list
Time limit: 500ms
Memory limit: 256mb
Description:
Based on Exercise 2, your task is to reverse the order of its nodes. It means originally, you have a linked list a -> b -> c -> null that storing 3 values a, b and c. Now you need to reverse the pointers in the list and make the list become c -> b -> a -> null. Noted that you don’t need to create any new node, only reverse the pointers.
Tips: You may traverse the whole list node by node, using three helper pointers (i.e. prev pointing to previous node, current pointing to current node, next pointing the next node). At each step, let current node point to previous node, then move forward.
For example, if currently prev points to a, current points to b, next points to c, then let node b points to a, then move prev, current, next forward.
Current step:
Current step:
- - - - - - - - - - - -
| a | | b | -> | c | -> null
- - - - - - - - - - - -
prev current next
After this step:
- - - - - - - - - - - -
| a | <- | b | | c | -> null
- - - - - - - - - - - -
prev current next
void reverse (List p);
Example:
reverse 1 -> 2 -> 3
List will be something like: 3 -> 2 -> 1
Sample input:
5
1 8 5 3 9
Sample output:
9 8 5 3 1
-------------------------Copy the following code, complete it and submit-------------------------
#include <stdio.h>
#include <stdlib.h>
typedef struct linked_list_node{
int value;
struct linked_list_node* next;
} Node;
typedef Node* List;
int Exist(List p, int value)
{
// judge whether linked list p contains the value
// you should visit each node of the linked list one by one, and check whether it is equal to the value
// if you find it then return 1, otherwise return 0
while(p!=NULL)
{
if(p->value==value) return 1;
p = p->next;
}
return 0;
}
void Print(List p)
{
// print all integers from the head of linked list in one line(separated by a space), in other words, you should firstly print the integer p points to
// to be more specific, print p->value and then move p to the next node p->next recursively, until p points to NULL
while(p!=NULL)
{
printf("%d ", p->value);
p = p->next;
}
printf("\n");
}
List Insert(List p, int value)
{
}
List Reverse(List p){
}
int main()
{
List p = NULL;
int n, m;
int value;
// printf("List initialization: \n");
// printf("How many integers in list initially: ");
scanf("%d", &n);
// printf("What are the integers: ");
for(int i=0; i<n; i++)
{
int value;
scanf("%d", &value);
p = Insert(p, value);
}
// printf("Reverse List: \n");
p = Reverse(p);
// printf("Current array: \n");
Print(p);
return 0;
}
-------------------------------------------End of Code-------------------------------------------
Submit