4. Write an algorithm in pseudo code to insert one element in a singly linked li
ID: 3588877 • Letter: 4
Question
4. Write an algorithm in pseudo code to insert one element in a singly linked list before a given element. Your algorithm will print the original list, request the user to put in an element to be inserted, and an element to indicate the location of the insertion, then print the final list after the insertion is done. If the element doesn’t exist in the list, add the new element to the end of the list.
Use the following as your test cases to evaluate whether your algorithm works correctly:
if you have a linked list: 3->1->0,
with user input 5 and 1, your list should become 3->5->1->0;
with user input 5 and -1, your list should become 3->1->0->5.
Explanation / Answer
/********************ListNode.java*****************************/
/**
* The Class ListNode.
*/
public class ListNode {
/** The data. */
private int data;
/** The next. */
private ListNode next;
public ListNode(int data) {
this.data = data;
this.next = null;
}
/**
* Gets the data.
*
* @return the data
*/
public int getData() {
return data;
}
/**
* Sets the data.
*
* @param data the data to set
*/
public void setData(int data) {
this.data = data;
}
/**
* Gets the next.
*
* @return the next
*/
public ListNode getNext() {
return next;
}
/**
* Sets the next.
*
* @param next the next to set
*/
public void setNext(ListNode next) {
this.next = next;
}
}
/**************************************ListNodeDriver.java************************************/
/**
* The Class ListNodeDriver.
*/
public class ListNodeDriver {
/** The head. */
private ListNode head;
/**
* Instantiates a new list node driver.
*/
public ListNodeDriver() {
head = null;
}
/**
* Insert.
*
* @param data the data
* @param element the element
*/
public void insert(int data, int element) {
ListNode temp = new ListNode(data);
if (head == null) {
head = temp;
return;
} else {
ListNode current = head, prev = head;
while (current != null) {
if (current.getData() == element) {
break;
}
prev = current;
current = current.getNext();
}
if (current == null) {
prev.setNext(temp);
} else {
temp.setNext(current);
prev.setNext(temp);
}
}
}
/**
* Display.
*/
public void display() {
ListNode temp = head;
while (temp != null) {
System.out.print(temp.getData() + "->");
temp = temp.getNext();
}
System.out.println("NULL");
}
/**
* The main method.
*
* @param args the arguments
*/
public static void main(String[] args) {
ListNodeDriver obj = new ListNodeDriver();
obj.insert(3, -1);
obj.insert(1, -1);
obj.insert(0, -1);
obj.insert(5, 1);
obj.insert(5, -1);
System.out.println("Displaying list content");
obj.display();
}
}
/**********************************output**********************************/
Displaying list content
3->5->1->0->5->NULL
Thnaks a lot. Please let me know if you have any doubt.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.