📜  门| GATE-CS-2014-(Set-1)|问题22(1)

📅  最后修改于: 2023-12-03 15:12:42.144000             🧑  作者: Mango

GATE-CS-2014-(Set-1) Problem 22

The following C function takes a singly-linked list as input argument. It modifies the list by moving the last element to the front of the list and returns the modified list. Some part of the code is left blank. Choose the correct alternative to fill in the blank line.

	#include<stdio.h>

	struct ListNode {
		int val;
		struct ListNode *next;
	};

	struct ListNode* MoveLastElementToFirst(struct ListNode *head) {
		if ((head == NULL) || (head->next == NULL)) {
			return head;
		}

		struct ListNode *seclast = NULL;
		struct ListNode *last = head;

		while (last->next != NULL) {
			seclast = last;
			last = last->next;
		}

		seclast->next = ____;
		last->next = head;
		head = last;

		return head;
	}

Solution

The function MoveLastElementToFirst() modifies the linked list by moving the last element to the front of the list. The first step is to check if the linked list is empty or if it contains only one node. If the list is empty or contains only one node, it is already sorted and the function returns the input list.

If there are two or more nodes in the list, we create two pointers seclast and last and traverse the linked list until we reach the last node. Once we reach the last node, we make the next pointer of the second to last node point to NULL and make the next pointer of the last node point to the head of the linked list. We then make the head pointer point to the last node, thus moving the last node to the front of the list.

The blank line can be filled by head. Since we want to move the last element to the front of the list, we make the next pointer of the second to last node point to NULL and the next pointer of the last node point to the head of the linked list. We then move the head pointer to the last node, effectively moving the last node to the front of the list.

Therefore, the correct solution is:

	seclast->next = NULL;
	last->next = head;
	head = last;
Time Complexity

The time complexity of this function is O(n), where n is the number of nodes in the linked list. This is because we need to traverse the entire linked list to get to the second to last node, which takes n-1 comparisons.

Space Complexity

The space complexity of this function is O(1), because we only need to create two pointers to traverse the linked list and we do not use any extra space.