Showing posts with label delete. Show all posts
Showing posts with label delete. Show all posts

Wednesday, 12 August 2015

Delete duplicate-value nodes from a sorted linked list

Problem Statement

You're given the pointer to the head node of a sorted linked list, where the data in the nodes is in ascending order. Delete as few nodes as possible so that the list does not contain any value more than once. The given head pointer may be null indicating that the list is empty.

For now do not be concerned with the memory deallocation. In common abstract data structure scenarios, deleting an element might also require deallocating the memory occupied by it. For an initial intro to the topic of dynamic memory please consult: http://www.cplusplus.com/doc/tutorial/dynamic/

Input Format You have to complete the Node* RemoveDuplicates(Node* head) method which takes one argument - the head of the sorted linked list. You should NOT read any input from stdin/console.

Output Format Delete as few nodes as possible to ensure that no two nodes have the same data. Adjust the next pointers to ensure that the remaining nodes form a single sorted linked list. Then return the head of the sorted updated linked list. Do NOT print anything to stdout/console.

Sample Input 1 -> 1 -> 3 -> 3 -> 5 -> 6 -> NULL NULL

Sample Output 1 -> 3 -> 5 -> 6 -> NULL NULL

Explanation 1. 1 and 3 are repeated, and are deleted. 2. Empty list remains empty.


Delete a Node

Problem Statement

You’re given the pointer to the head node of a linked list and the position of a node to delete. Delete the node at the given position and return the head node. A position of 0 indicates head, a position of 1 indicates one node away from the head and so on. The list may become empty after you delete the node.

Input Format You have to complete the Node* Delete(Node* head, int position) method which takes two arguments - the head of the linked list and the position of the node to delete. You should NOT read any input from stdin/console. position will always be at least 0 and less than the number of the elements in the list.

Output Format Delete the node at the given position and return the head of the updated linked list. Do NOT print anything to stdout/console.

Sample Input

1 --> 2 --> 3 --> NULL, position = 0 1 --> NULL , position = 0

Sample Output 2 --> 3 --> NULL NULL

Explanation 1. 0th position is removed, 1 is deleted from the list. 2. Again 0th position is deleted and we are left with empty list.