📅  最后修改于: 2023-12-03 15:42:17.670000             🧑  作者: Mango
This is a sample question from the GATE-CS-2015 (Set 3) paper, section 65.
Consider the following C function. The function takes a single-linked list of integers as input parameter. It modifies the list by moving the last element to the front of the list, and returns the modified list. Assume that the list has at least one element.
struct node {
int value;
struct node *next;
};
struct node * modify_list(struct node *head) {
struct node *last = head, *second_last = NULL;
while (last->next != NULL) {
second_last = last;
last = last->next;
}
second_last->next = NULL;
last->next = head;
head = last;
return head;
}
The given code takes a single-linked list of integers as input parameter and modifies the list by moving the last element to the front of the list.
The modify_list
function starts by pointing two pointers last
and second_last
to the first node of the linked list. It then traverses the linked list until last
pointer points to the last node of the linked list and second_last
points to the second last node of the linked list.
Once last
pointer points to the last node, second_last->next
is set to NULL
, breaking the link between the last and second last node. last->next
is then set to point to the head of the linked list, effectively moving the last node to the front of the list. Finally, the head
pointer is updated to point to the new head of the list and returned.
This code can be used to move the last element of a single-linked list to the front of the list. It can be a useful utility function for modifying linked lists in programming problems.
struct node {
int value;
struct node *next;
};
struct node * modify_list(struct node *head) {
struct node *last = head, *second_last = NULL;
while (last->next != NULL) {
second_last = last;
last = last->next;
}
second_last->next = NULL;
last->next = head;
head = last;
return head;
}