127k views
20 votes
Extend the class linkedListType by adding the following operations: Write a function that returns the info of the kth element of the linked list. If no such element exists, terminate the program. Write a function that deletes the kth element of the linked list. If no such element exists, terminate the program.

1 Answer

5 votes

Answer:

Step-by-step explanation:

The following code is written in Java. Both functions traverse the linkedlist, until it reaches the desired index and either returns that value or deletes it. If no value is found the function terminates.

public int GetNth(int index)

{

Node current = head;

int count = 0;

while (current != null)

{

if (count == index)

return current.data;

count++;

current = current.next;

}

assert (false);

return 0;

}

public int removeNth(int index)

{

Node current = head;

int count = 0;

while (current != null)

{

if (count == index)

return current.remove;

count++;

current = current.next;

}

assert (false);

return 0;

}

User Coanor
by
2.9k points