Question

Consider the following code to insert an item in a sorted linked list without a dummy...

Consider the following code to insert an item in a sorted linked list without a dummy node.

 60  public void insert(T t) {
 61    Node p;
 62    for (p = head; head != null; p = p.next)
 63      if (p.data.compareTo(t) > 0) break;
 64    if (p == head) p = new Node(t, head);
 65    else p.next = new Node(t,p);
 66  }
  1. If we insert the value 5 into an empty list, nothing happens. The list stays empty. Why did we get this problem? Fix the bug.
  2. Now assume we have successfully inserted 5 into an empty sequence. If we then try to insert the value 7, it crashes with a “null pointer exception” on line 63. In the debugger it says that p is null. There's a simple thing wrong with the loop header on line 62. What? Fix it. (This doesn't fix the full problem, of course.)
  3. Once we fix that problem, it still crashes when we attempt to insert 7 into the list, this time on the `else' line (line 65). Again the debugger says that p is null. What happened? Fix the bug. This will require a bigger change.
  4. Depending on how you fixed the previous bug, there may still be nasty bugs.
0 0
Add a comment Improve this question Transcribed image text
Answer #1

Here is the corrected code for this method. Fixes are highlighted in bold text. Let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. Thanks

Explanation: The first bug (inserted element not getting displayed) was because the head node wasn’t getting updated, the next bug was due to the error in for loop condition, and all the remaining bugs were due to the incorrect logic (related to the Node object p)

public void insert(T t) {

                Node p;

                // creating another Node to store the previous node of p

                Node prev = null;

                // updated for loop (condition has been fixed)

                for (p = head; p != null; p = p.next) {

                                if (p.data.compareTo(t) > 0)

                                               break;

                                // storing p in prev, before moving to next iteration

                                prev = p;

                }

                if (p == head) {

                                p = new Node(t, head);

                                head = p; // updating head to fix the error

                } else {

                                // simple fix to solve all the nasty bugs

                                //adding the new node between prev and p

                                prev.next = new Node(t, p);

                }

}

Add a comment
Know the answer?
Add Answer to:
Consider the following code to insert an item in a sorted linked list without a dummy...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • this is i have code for double linked list with insert at sorted list. i have...

    this is i have code for double linked list with insert at sorted list. i have some error that stdout: ------- Error: compilation stderr: ------- InsertDouble.c: In function ‘list* InsertDouble(LIST, int)’: InsertDouble.c:51:14: error: cannot convert ‘list’ to ‘list*’ in assignment Currentptr = *head; // set a pointer which is current one ^ it keep give me this error i am not sure how to fix is anyone possible to help me? #include <stdio.h> #include <stdlib.h> typedef struct list {   ...

  • Problem 2: based on java.util.LinkedList class, create MyStack class that should have the methods: push(), pop(),...

    Problem 2: based on java.util.LinkedList class, create MyStack class that should have the methods: push(), pop(), peek(), size(), isEmpty(). my linkedlist class is: public class Lab8_problem1 {    private Node head, tail; private int size;    public Lab8_problem1() { this.head = null; this.tail = null; this.size = 0; } //Insert a node at specifc Location public void insertAt(int value, int index) { Node newNode = new Node(); newNode.data = value; if(head == null){ head = newNode; tail = newNode; head.next...

  • c++ modify the attached unsorted linked list class into a sorted linked list class #include <iostream>...

    c++ modify the attached unsorted linked list class into a sorted linked list class #include <iostream> using namespace std; template<class T> struct Node {     T data;//data field     Node * next;//link field     Node(T data) {       this->data = data;     } }; template<class T> class linked_list{ private:       Node<T> *head,*current; public:       linked_list(){//constructor, empty linked list         head = NULL;         current = NULL;       }       ~linked_list(){         current = head;         while(current != NULL) {          ...

  • C++: I need implement this code using Double Linked List using the cosiderations 1. head point...

    C++: I need implement this code using Double Linked List using the cosiderations 1. head point to null in an empty list 2. There is not need of a tail pointer /*This class implements the singly linked list using templates Each list has two attributes:    -head: first node in the list    -tail: last node in the list #include "circDLLNode.h" template class { public:    //Default constructor: creates an empty list    ();    //Destructor: deallocate memory    ~();  ...

  • BELOW IS THE CODE I ALREADY HAVE Linked List - Delete Modify Lab 5 and include...

    BELOW IS THE CODE I ALREADY HAVE Linked List - Delete Modify Lab 5 and include the method to delete a node from the Linked List. In summary: 1) Add the method Delete 2) Method call to delete, with a number that IS in the list 3) Method call to delete, with a number that is NOT in the list - Be sure to include comments - Use meaningful identifier names (constants where appropriate) import java.io.*; 1/ Java program to...

  • Using the provided Linked List example code, linkedlist.c, as an example Make a node struct that...

    Using the provided Linked List example code, linkedlist.c, as an example Make a node struct that holds ints instead of strings. In your main, insert 25 to 75 random integers with range (0 to 100) into a linked list of your nodes. Use a random to determine how many to make. Write a function int sum(NodePointer current) that returns the sum of the integers in the list by looping through the linked list. Write a function int count(NodePointer current) that...

  • In C++, Modify the following code of a single linked list, so insted of doing sort...

    In C++, Modify the following code of a single linked list, so insted of doing sort insert in descending order, to do it in ascending order: template <class T> void IntSLList<T>::sortInsert(T val) {    //if empty the list    if (head == 0)    {        //add as node to head with data as val        addToHead(val);    }    //if not empty    else    {        //create to pointers to the list        IntSLLNode<T>...

  • Design and implement your own linked list class to hold a sorted list of integers in...

    Design and implement your own linked list class to hold a sorted list of integers in ascending order. The class should have member function for inserting an item in the list, deleting an item from the list, and searching the list for an item. Note: the search function should return the position of the item in the list (first item at position 0) and -1 if not found. In addition, it should member functions to display the list, check if...

  • Design and implement your own linked list class to hold a sorted list of integers in ascending order. The class should h...

    Design and implement your own linked list class to hold a sorted list of integers in ascending order. The class should have member function for inserting an item in the list, deleting an item from the list, and searching the list for an item. Note: the search function should return the position of the item in the list (first item at position 0) and -1 if not found. In addition, it should member functions to display the list, check if...

  • Using the provided Linked List template, add the following recursive functions and demonstrate them in a...

    Using the provided Linked List template, add the following recursive functions and demonstrate them in a separate cpp file. Write a recursive function to print the list in order. Write a recursive function to print the list in reverse order. Write a recursive function to print every other node in the list in order. Write a recursive function to return the number of nodes in the list. Write a Boolean function that implements the recursive version of sequential search. THIS...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT