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 {   ...

  • 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) {          ...

  • 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...

  • 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...

  • starter code To write a program using the starter code which is TestLinkedList to see if...

    starter code To write a program using the starter code which is TestLinkedList to see if the LinkedList program has bugs. It will produce ether a pass or fail.More information is in the first two pictures. LinkedList.java /** * @author someone * * Implements a double-linked list with four errors */ public class LinkedList<E> { // The first and last nodes in the list private Node<E> head, tail; // Number of items stored in the list private int size; //...

  • n JAVA, students will create a linked list structure that will be used to support a...

    n JAVA, students will create a linked list structure that will be used to support a role playing game. The linked list will represent the main character inventory. The setting is a main character archeologist that is traveling around the jungle in search of an ancient tomb. The user can add items in inventory by priority as they travel around (pickup, buy, find), drop items when their bag is full, and use items (eat, spend, use), view their inventory as...

  • Doubly Linked List The assignment is to modify the below code in any way (like changing the method of a function). Time...

    Doubly Linked List The assignment is to modify the below code in any way (like changing the method of a function). Time complexity is omitted. Any methods/functions below could be changed into something different. I was thinking of changing the method of getting size of list and maybe change from numbers to letters for nodes. import java.util.Scanner; /* Class Node */ class Node { protected int data; protected Node next, prev; /* Constructor */ public Node() { next = null;...

  • C++ Create a class that implements a sorted, doubly-linked list: Start with a copy of the...

    C++ Create a class that implements a sorted, doubly-linked list: Start with a copy of the sortedList class. Call your new class doublyLinkedList. Convert the baseline code into a doubly linkedlist, and thoroughly test all existing operations (make sure to check all edge conditions), and then implement the new operations below. The class should have the following additional class methods: • A reverse method: this method will reverse the order of the doubly linked list. This method takes no parameters,...

  • Im making a generic linked list. I cant figure out how to make an object of...

    Im making a generic linked list. I cant figure out how to make an object of my class from main. My 3 files are main.cpp dan.h dan.cpp The error is: 15 6 [Error] prototype for 'void ll<T>::insert()' does not match any in class 'll<T>' #include <iostream> #include <string> #include "dan.h" using namespace std; int main() { ll<int> work; work.insert(55);//THIS IS THE LINE THATS GIVING ME THE ERROR, Without this line it compiles and //runs. } #ifndef DAN_H #define DAN_H #include...

  • LAB: Inserting an integer in descending order (doubly-linked list) Given main() and an IntNode class, complete...

    LAB: Inserting an integer in descending order (doubly-linked list) Given main() and an IntNode class, complete the IntList class (a linked list of IntNodes) by writing the insertInDescendingOrder() method to insert new IntNodes into the IntList in descending order. Ex. If the input is: 3 4 2 5 1 6 7 9 8 -1 the output is: 9 8 7 6 5 4 3 2 1 ___________________________________________________________________________________________________________________________________________________ SortedList.java (READ ONLY!!!) import java.util.Scanner; public class SortedList { public static void main...

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
ADVERTISEMENT