Programming Fundamentals
Download list_reverse.c here
Or, copy these file(s) to your CSE account using the following command:
1511 fetch-activity list_reverse
Your task is to add code to this function in list_reverse.c:
//
// Place the list pointed to by head into reverse order.
// The head of the list is returned.
//
struct node *reverse(struct node *head) {
// PUT YOUR CODE HERE (change the next line!)
return NULL;
}
Note list_reverse.c
uses the following familiar data type:
struct node { struct node *next; int data; };
list_reverse
is given one argument, head
which is the pointer to the first
node in the linked list.
Add code to reverse
which rearranges the list to be in reverse order.
reverse
should return a pointer to the new list.
reverse
must rearrange the list by changing the next
fields of nodes.
reverse
must not change the data
fields of nodes.
For example if the linked list contains these 8 elements:
16, 7, 8, 12, 13, 19, 21, 12
reverse
should return a pointer to a list with these elements:
12, 21, 19, 13, 12, 8, 7, 16
Testing
list_reverse.c
also contains a main
function which allows you to test your
list_reverse
function.
This main function:
- takes in the size of the linked list,
- converts the input numbers to a linked list,
- assigns a pointer to the first node in the linked list to
head
, - calls
reverse(head)
and - prints the result.
Do not change this function. If you want to change it, you have misread the question.
Your list_reverse
function will be called directly in marking. The main
function is only to let you test your list_reverse
function
Examples
dcc list_reverse.c -o list_reverse ./list_reverse How many numbers in list?: 8 16 7 8 12 13 19 21 12 [12, 21, 19, 13, 12, 8, 7, 16] ./list_reverse How many numbers in list?: 6 2 4 6 2 4 6 [6, 4, 2, 6, 4, 2] ./list_reverse 42 How many numbers in list?: 1 42 [42] ./list_reverse How many numbers in list?: 0 []
Assumptions/Restrictions/Clarifications
list_reverse
should not change the data fields of list nodeslist_reverse
should not use arrayslist_reverse
should not callmalloc
list_reverse
should not call scanf (orgetchar
orfgets
)list_reverse
should not print anything. It should not callprintf
- Do not change the supplied
main
function. It will not be tested or marked