Question

Linked list delete trouble

Asked by: Stealthrt

Hey all i am in need of some help with getting some nodes deleted. This is the situation:

Right now it only deletes the 1 string i pass to it "deleteItem". However, i wish to delete the next 8 blocks after the "deleteItem".

Say i have this in the list right now.

bob barker is pretty old but still seems to get all the ladies

Now the user would pick "bob" and the code would delete "bob" but leave everything else. I wish to take out "bob, barker, is, pretty, old, but, still, seems, to".

So....
bob <delete>
move to next node..
barker <delete>
move to next node..
is <delete>
...etc etc.

I have attached the 3 txt files of this project along with the code below that is responsible for deleting the node string.

I'm unsure on how to go about doing that. Any help would be great!

David

Part of unorderedLinkedList.h:
 
template <class Type>
void unorderedLinkedList<Type>::deleteNode(const Type& deleteItem)
{
    nodeType<Type> *current; //pointer to traverse the list
    nodeType<Type> *trailCurrent; //pointer just before current
    bool found;
 
    if (first == NULL)    //Case 1; the list is empty. 
        cout << "Cannot delete from an empty list."
             << endl;
    else
    {
        if (first->info == deleteItem) //Case 2 
        {
            current = first;
            first = first->link;
			nodeType<Type> *next;
			
            count--;
            if (first == NULL)    //the list has only one node
                last = NULL;
 
            delete current;
			
        }
        else //search the list for the node with the given info
        {
            found = false;
            trailCurrent = first;  //set trailCurrent to point
                                   //to the first node
            current = first->link; //set current to point to 
                                   //the second node
 
            while (current != NULL && !found)
            {
                if (current->info != deleteItem) 
                {
                    trailCurrent = current;
                    current = current-> link;
                }
                else
                    found = true;
            }//end while
 
            if (found) //Case 3; if found, delete the node
            {
                trailCurrent->link = current->link;
                count--;
 
                if (last == current)   //node to be deleted 
                                       //was the last node
                    last = trailCurrent; //update the value 
                                         //of last
                delete current;  //delete the node from the list
            }
            else
                cout << "The item to be deleted is not in "
                     << "the list." << endl;
        }//end else
    }//end else
}//end deleteNode
 
 
 
mainfile.cpp:
 
#include <string>
#include "unorderedLinkedList.h"
    
using namespace std;
 
int main()
{
    unorderedLinkedList<string> list1;
    string str;
 
    cout << "Enter 10 strings." << endl; 
 
    for (int i = 0; i < 10; i++)
    {
        cin >> str;
        list1.insertLast(str);
    }
 
    cout << endl;
 
    list1.print();
    cout << endl;
 
    cout << "Enter the string to be "
         << "deleted: ";
    cin >> str;
    cout << endl;
	
    list1.deleteNode(str);
	
    cout << "After deleting " << str << endl;
    list1.print();
    cout << endl;
 
    system("pause");					
}
                                  
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81:
82:
83:
84:
85:
86:
87:
88:
89:
90:
91:
92:
93:
94:
95:
96:
97:
98:
99:
100:
101:
102:
103:
104:

Select allOpen in new window

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2009-10-19 at 14:42:28ID24825205
Topics

C++ Programming Language

,

Microsoft Visual C++.Net

Participating Experts
2
Points
125
Comments
46

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. Treeviews & nodes
    I have a treeview and i wish to add to it at runtime but i am having real trouble adding nodes I am loading data from a file in the form e.g stock bags|white bags|100 - 200 inch|$1.23| stock bags|white bags|200 - 300 inch|$1.24| stock bags|white bags|300 - 400 inch|$1.26| st...
  2. Unsure of the isqlt09a.dll
    I cannot find the isqlt09a.dll on my machine, but Apache needs it to run - at least that is what the error message says. Does anyone know of this dll?
  3. Deleting multiple nodes in treeview
    What I want to know - is my solution okay? Does someone have other ideas? Thanks. I have noticed that once I delete a node, VB renumbers the remaining nodes in the treeview This is a problem - because I need to be able to delete nodes that contain certain substrings in the ...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: Infinity08Posted on 2009-10-19 at 15:22:03ID: 25609514

When you have found the target node ("bob" in your example), keep a pointer to the previous node - you'll need it later. Then start following the linked list, and delete every node you traverse, until you've deleted the amount you want (8 in your example). Now all you have to do is connect the node you kept a pointer to earlier with the next node (the node just after the last one that was deleted).

 

by: StealthrtPosted on 2009-10-19 at 15:55:06ID: 25609693

Infinity08:

Mind giving me an example of all that?

Thanks! :o)

David

 

by: StealthrtPosted on 2009-10-19 at 19:18:59ID: 25610597

Sorry i understand the concept in text but when it comes to programming it with my code, i dont.

David

 

by: Infinity08Posted on 2009-10-20 at 03:08:14ID: 25612469

Which part are you confused about ?

Your current code seems to correctly delete one node from the linked list. You can repeat this deletion process 8 times (in a loop) to delete 8 consecutive nodes.
Keep trailCurrent pointing to the node before those 8, and use current to move over the 8 nodes, and delete them along the way. At the end, all you have to do is update the next pointer for the trailCurrent node (just like you're already doing), and possibly update the last pointer.

 

by: itsmeandnobodyelsePosted on 2009-10-20 at 08:39:28ID: 25615274

Instead of a loop you also could rename your deleteNode into deleteItem and have a new member function deleteNode which can be called recursively:

pseudocode:

  deleteItem(item)
  {
      NodePtr find = findNode(item)
      if  find is not null
            deleteNode(find)
      else
           output "empty list"
  }
 
The findNode would iterate from First until "item" was found. The the current node was returned. If not found NULL was returned.

The deleteNode would check whether the next node is not NULL and if so would call deleteNode passing the next. After the call it would delete the node passed.

That way "Bob" would call deleteNode for "Barker", "Barker" would call deleteNode for "is" and so on and after the whole branch after was deleted, it would delete the node itself.  

 

by: StealthrtPosted on 2009-10-20 at 13:11:18ID: 25618023

Infinity08: K... I tried this thinking that this is what your talking about:

But i get an error after it prints out the list after the delete.
Unhandled exception at 0x0041d7f6 in linkedlists.exe: 0xC0000005: Access violation reading location 0xfeeeff02.

current = first;
            first = first->link;
			trailCurrent = first;
			
            count--;
            if (first == NULL)    //the list has only one node
                last = NULL;
			
            delete current;
 
			current = trailCurrent->link;
 
			delete current;
 
			system("pause");

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:

Select allOpen in new window

 

by: Infinity08Posted on 2009-10-20 at 14:12:09ID: 25618679

I'm not sure what the piece of code you just posted is intended to do ...

Could you maybe post the entire deleteNode function again, after your modifications.

 

by: StealthrtPosted on 2009-10-20 at 14:21:35ID: 25618775

template <class Type>
void unorderedLinkedList<Type>::deleteNode(const Type& deleteItem)
{
    nodeType<Type> *current; //pointer to traverse the list
    nodeType<Type> *trailCurrent; //pointer just before current
    bool found;
 
    if (first == NULL)    //Case 1; the list is empty. 
        cout << "Cannot delete from an empty list."
             << endl;
    else
    {
        if (first->info == deleteItem) //Case 2 
        {
            current = first;
            first = first->link;
                        trailCurrent = first;
                        
            count--;
            if (first == NULL)    //the list has only one node
                last = NULL;
                        
            delete current;
 
            current = trailCurrent->link;
 
            delete current;
 
            system("pause");
        }
        else //search the list for the node with the given info
        {
            found = false;
            trailCurrent = first;  //set trailCurrent to point
                                   //to the first node
            current = first->link; //set current to point to 
                                   //the second node
 
            while (current != NULL && !found)
            {
                if (current->info != deleteItem) 
                {
                    trailCurrent = current;
                    current = current-> link;
                }
                else
                    found = true;
            }//end while
 
            if (found) //Case 3; if found, delete the node
            {
                trailCurrent->link = current->link;
                count--;
 
                if (last == current)   //node to be deleted 
                                       //was the last node
                    last = trailCurrent; //update the value 
                                         //of last
                delete current;  //delete the node from the list
            }
            else
                cout << "The item to be deleted is not in "
                     << "the list." << endl;
        }//end else
    }//end else
}//end deleteNode

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:

Select allOpen in new window

 

by: Infinity08Posted on 2009-10-20 at 14:54:18ID: 25619049

Ok.

I suggest making a drawing of a linked list (each node represented by a box, with arrows between the representing the links).

Then, re-arrange the arrows repeatedly to remove one node at a time from the linked list. Once you understand how it works on paper, you can implement it.

deleting one node from a linked list goes something like this (where 'node' points to the node just before the one we want to delete) :

        tmp = node->next;                            // tmp now points to the node that has to be deleted
        node->next = node->next->next;     // we bypass the node that will be deleted, and point to the one after that
        delete tmp;                                        // and the node is deleted

To delete multiple nodes, these same three lines are just repeated as needed.

And then to finish it all off, you have to take into account the special cases (like the start and the end of the linked list).

 

by: StealthrtPosted on 2009-10-24 at 14:45:53ID: 25654516

I am unable to get it to work in my code infinity08:

tmp = first->next;
first->next = first->next->next;
delete tmp;

                                              
1:
2:
3:

Select allOpen in new window

 

by: Infinity08Posted on 2009-10-24 at 14:50:59ID: 25654533

It was just a quick overview of the operations that need to be done. You don't have to copy it literally. You have to understand it, and then adapt it to your situation.

 

by: StealthrtPosted on 2009-10-24 at 14:56:37ID: 25654546

The error it gives me is:

error C2039: 'next' : is not a member of 'nodeType<Type>'  with [Type=std::string]

David

 

by: StealthrtPosted on 2009-10-24 at 14:57:45ID: 25654551

I understand it, infinity but i cant seem to work it out in code. I know it needs to point to the node in the next node but i am unable to figure out how to go about doing that since there is no "NEXT" in my code.

David

 

by: itsmeandnobodyelsePosted on 2009-10-25 at 00:21:05ID: 25655803

>>>> error C2039: 'next' : is not a member of 'nodeType<Type>'  with [Type=std::string]


The 'next' member is called 'link' in your node template class nodeType.

So replace

   tmp = first->next;
   first->next = first->next->next;
   delete tmp;

by

   tmp = first->link;
   first->link = first->link->link;
   delete tmp;


A tip: if ever you got such an error message from the compiler: take it literally.

The message above clearly said  'next' is NOT a member of nodeType what is true as the member name is 'link'.

 

by: Infinity08Posted on 2009-10-25 at 00:58:39ID: 25655900

>> I know it needs to point to the node in the next node

Indeed.

>> but i am unable to figure out how to go about doing that since there is no "NEXT" in my code.

So, what could you use instead of 'next' in your code ?

But I see Alex already came to the rescue ...

 

by: StealthrtPosted on 2009-10-25 at 15:38:57ID: 25658808

Great! It works now :o) But this time it skips the previous one and just takes the one that is entered and then however many i deside to delete thereafter.

I tried using:

tmp = current->link;
first->link = first->link->link;
delete tmp;

and

tmp = trailCurrent;
first->link = first->link->link;
delete tmp;

but did nothing.

template <class Type>
void unorderedLinkedList<Type>::deleteNode(const Type& deleteItem)
{
    nodeType<Type> *current;
    nodeType<Type> *trailCurrent;
	nodeType<Type> *tmp;
	bool found;
 
    if (first == NULL)
        cout << "Cannot delete from an empty list." << endl;
    else
    {
		found = false;
		trailCurrent = first;
		current = first->link;
 
		while (current != NULL && !found)
		{
			if (current->info != deleteItem) 
			{
                trailCurrent = current;
                current = current-> link;
            }else
			{
				found = true;
            }
 
            if (found)
            {
                trailCurrent->link = current->link;
                count--;
 
                if (last == current)
				{
                    last = trailCurrent;
				}
 
				cout << first->info << endl;
 
                tmp = first->link;
				first->link = first->link->link;
				delete tmp;
 
				tmp = first->link;
				first->link = first->link->link;
				delete tmp;
 
				tmp = first->link;
				first->link = first->link->link;
				delete tmp;
            }else
			{
                cout << "The item to be deleted is not in the list." << endl;
			}
        }
    }
}

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:

Select allOpen in new window

 

by: Infinity08Posted on 2009-10-26 at 02:04:34ID: 25660584

>> But this time it skips the previous one

What do you mean ? If you want to start deleting from the previous one, then you just have to make sure to point to one node earlier ...

 

by: itsmeandnobodyelsePosted on 2009-10-26 at 02:49:43ID: 25660744

>>>> tmp = current->link;
>>>> first->link = first->link->link;
>>>> delete tmp;

The sequence above is for deleting one single node in the chain and chaining (linking) the previous with the next, e. g. if you have a list with 6 nodes

   RN -> N1 -> N2 -> N3 -> N4 -> N5 -> 0

and current is N2, then the above code would unlink the N3 and delete it and would link N2 to N4.

     RN -> N1 -> N2 -> N4 -> N5 -> 0

So, if you would like to delete N4 and N5 as well you would need to keep the N2 as current and repeat the above sequence until current->link is NULL.

But actually the deleteNode rarely will/should delete more than one node but only one node. You would iterate from root until you find the node you want to delete, then make the previous of the found node the current (deleting the root node would be a special case to handle) and apply the above statements. You best safe the 'previous' node with each iteration so that the pointer variable already is filled when you found the node to delete.




 

by: StealthrtPosted on 2009-10-26 at 16:36:54ID: 25668094

I thought thats what i was doing with this code, itsmeandnobodyelse:

tmp = trailCurrent;
first->link = first->link->link;
delete tmp;

But i get an error of:
Unhandled exception at 0x0041b6d3 in linkedlists.exe: 0xC0000005: Access violation reading location 0xfeeeff0a.

and thats on the line of the next node:

tmp = first->link;
first->link = first->link->link;    // <-error on this line
delete tmp;

Right now i have "bob, barker, 1, 2, 3, 4, 5, 6, 7, 8" and when i type in barker it shows this:

bob, 6, 7, 8

However, when the user types in barker, i need it to take away bob as well. Thats where i am stuck and thought the code above was taking the previous node (bob) and deleting that as well..

David

 

by: itsmeandnobodyelsePosted on 2009-10-26 at 16:48:09ID: 25668142

>>>> Access violation reading location 0xfeeeff0a.

Hmm. You are dealing with tmp and trailCurrent but the delete statements operate with first and first->link. If any of those isn't valid it makes kaboom.

Pointers need carefulness. Always check a pointer to be valid before accessing it.

if (first != NULL && first->link != NULL)
{
     // now the statement is safe
     first->link = first->link->link;
}

Can you tell what trailCurrent is? And why you use 'first' instead of 'previous'  as in the code I posted?

 

by: StealthrtPosted on 2009-10-26 at 20:41:42ID: 25668986

trailCurrent = first;
current = first->link;

and "first" is defined in the header file

David

 

by: Infinity08Posted on 2009-10-27 at 00:03:35ID: 25669649

Could we go back to http:#25660584, and start again from there, Stealthrt ? Your code worked at that point, except that it didn't delete the right set of nodes. So, all you had to do, is modify your code there to start deleting at a different node ...

Try that again, and post your modified code here if it doesn't work.

 

by: itsmeandnobodyelsePosted on 2009-10-27 at 00:21:20ID: 25669755

To add to above comment.

In order that the following code should not crash

>>>> tmp = current->link;
>>>> current->link = current->link->link;
>>>> delete tmp;


the linked list must contain at least two valid nodes: current and current->link

The situation where a list has only one node left must be handled seperately.

 

by: StealthrtPosted on 2009-10-27 at 12:51:42ID: 25676644

Alright, i did as you suggested infinity08 but it seems to delete the one before it now BUT now doesn't delete the one that was chosen....

Here is the output:

bob
barker
1
2
3
4
5
6
7
8

Enter the string to be deleted: barker

After deleting barker
barker
5
6
7
8

Press any key to continue . . .

David

template <class Type>
void unorderedLinkedList<Type>::deleteNode(const Type& deleteItem)
{
    nodeType<Type> *current;
    nodeType<Type> *trailCurrent;
	nodeType<Type> *tmp;
	bool found;
 
    if (first == NULL)
        cout << "Cannot delete from an empty list." << endl;
    else
    {
		found = false;
		trailCurrent = first;
		current = first->link;
 
		while (current != NULL && !found)
		{
			if (current->info != deleteItem) 
			{
                trailCurrent = current;
                //current = current-> link;
            }else
			{
				found = true;
            }
 
            if (found)
            {
                //trailCurrent->link = current->link;
                count--;
 
                if (last == current)
				{
                    last = trailCurrent;
				}
 
				//delete trailCurrent;
 
                current = first;
				first = first->link;
                trailCurrent = first;
 
				if (first == NULL)    //the list has only one node
                last = NULL;
                        
				delete current;
 
				tmp = first->link;
				first->link = first->link->link;
				delete tmp;
 
				tmp = first->link;
				first->link = first->link->link;
				delete tmp;
 
				tmp = first->link;
				first->link = first->link->link;
				delete tmp;
 
				tmp = first->link;
				first->link = first->link->link;
				delete tmp;
            }else
			{
                cout << "The item to be deleted is not in the list." << endl;
			}
        }
    }
}

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:

Select allOpen in new window

 

by: Infinity08Posted on 2009-10-27 at 13:04:31ID: 25676813

>>             trailCurrent = first;
>>             current = first->link;

What if the item to be deleted is in the first node ?


>>                 trailCurrent = current;
>>                 //current = current-> link;

Why did you comment that second line ?


>>             }else
>>                   {
>>                         found = true;
>>             }

I think you're missing a closing } ... Properly indenting your code will help avoid this kind of mistake.


>>                 current = first;
>>                         first = first->link;
>>                 trailCurrent = first;

Why are you starting over ? You already found the first node that needs to be deleted.

 

by: StealthrtPosted on 2009-10-27 at 13:20:40ID: 25676992

The item will never be the first node. It will go by last name and last name is going to be the second node. I took out the comment slashes and i get this now:


bob
barker
1
2
3
4
5
6
7
8

Enter the string to be deleted: barker

After deleting barker
1
6
7
8

Press any key to continue . . .

notice that it now deletes "bob" but leave "1" now.. gerr! This is so crazy. What do i need to change this:

tmp = first->link;
first->link = first->link->link;
delete tmp;

in order for it to delete the 1 as well?

David

 

by: Infinity08Posted on 2009-10-27 at 13:25:00ID: 25677023

>> Why are you starting over ? You already found the first node that needs to be deleted.

Just think about this question ^

The first while loop was there to find the first node to be deleted.

Once you found that node (after the while loop), you need to start deleting the amount of nodes you want, starting with that node.

 

by: StealthrtPosted on 2009-10-27 at 13:39:33ID: 25677180

Alright, this is what i have tried and they all have given me errors:

tmp = current;
first->link = first->link;
delete tmp;
 
and
 
tmp = current;
first->link = first->link->link;
delete tmp;
 
and
 
tmp = first;
first->link = first->link->link;
delete tmp;
 
and
 
tmp = first;
first->link = first->link;
delete tmp;
 
and
 
tmp = trailCurrent;
first->link = first->link->link;
delete tmp;
 
and
 
tmp = trailCurrent;
first->link = first->link;
delete tmp;

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:

Select allOpen in new window

 

by: Infinity08Posted on 2009-10-27 at 13:43:30ID: 25677222

Why do you think you need to start from first again ?

current is already pointing to the node that needs to be deleted. Just delete that node, and the nodes after it. Do NOT use first. first is the start of the linked list, and you don't want to start deleting there.

 

by: StealthrtPosted on 2009-10-27 at 13:48:29ID: 25677274

I must be missing something because i try this and it does not worth either:

tmp = trailCurrent;
trailCurrent->link = trailCurrent->link->link;
delete tmp;

David

 

by: Infinity08Posted on 2009-10-27 at 13:51:42ID: 25677313

>> trailCurrent->link = trailCurrent->link->link;

This skips the current node, so you also need to delete the current node.

 

by: StealthrtPosted on 2009-10-27 at 13:54:58ID: 25677351

Ok. This still brings an error:

tmp = trailCurrent;
trailCurrent->link = trailCurrent->link;
delete tmp;

I must be going all around the answer....

David

 

by: Infinity08Posted on 2009-10-27 at 14:02:47ID: 25677439

>> Ok. This still brings an error:

Don't just guess. Think about it.


What effect do you think this line has :

>> trailCurrent->link = trailCurrent->link;

? None at all.


You want to delete the node that is pointed to by 'current'.
And you want trailCurrent->link to point to the node after the 'current' node.

Do you understand why ? Do you understand how deleting a node in a linked list works ?
Take a look at this image, and that will hopefully make things clearer :

        http://en.wikipedia.org/wiki/File:Singly_linked_list_delete_after.png

 

by: StealthrtPosted on 2009-10-27 at 14:35:32ID: 25677833

Yes it makes since but like i said, i cant seem to code it like that.

David

 

by: Infinity08Posted on 2009-10-27 at 14:57:08ID: 25678054

>> Yes it makes since but like i said, i cant seem to code it like that.

Why not ?

Remember these three lines I posted earlier :

>>         tmp = node->next;                            // tmp now points to the node that has to be deleted
>>         node->next = node->next->next;     // we bypass the node that will be deleted, and point to the one after that
>>         delete tmp;                                        // and the node is deleted

? If 'node' points to the node before the one that needs to be deleted, then after these 3 lines, that node will be deleted from the linked list.

So, how does that apply to 'trailCurrent' and 'current', if 'current' is the one you want to delete ? Refer to the image if it isn't clear.

 

by: StealthrtPosted on 2009-10-27 at 15:03:45ID: 25678125

current can not be used since it was already deleted....

tmp = current;
current->link = current->link->link;
delete tmp;

David

 

by: Infinity08Posted on 2009-10-27 at 15:10:15ID: 25678175

>> current can not be used since it was already deleted....

What do you mean ? The first time, it's pointing to the node that needs to be deleted. After deleting the node, you make it point to the next one, so that it too can be deleted, etc.


>> tmp = current;
>> current->link = current->link->link;
>> delete tmp;

Ok. Again.

trailCurrent points to the node BEFORE the one that needs to be deleted.
current points to the node that needs to be deleted.

Then you need to execute some code that does a few things :

(a) trailCurrent->link needs to point to the node AFTER the one that needs to be deleted (we skip it)
(b) the node to be deleted needs to be deleted
(c) current now needs to point to the following node that needs to be deleted

Repeat as necessary.

 

by: StealthrtPosted on 2009-10-27 at 15:25:30ID: 25678354

I dont see how trailCurrent is used after it has been deleted by current

trailCurrent->link = current->link;
count--;

if (last == current)
{
last = trailCurrent;
}

current = first;
first = first->link;
trailCurrent = first;

if (first == NULL)
last = NULL;
                       
delete current;

tmp = current;
current->link = current->link->link;
delete tmp;

since trailCurrent  points right back to the first node..

David

 

by: itsmeandnobodyelsePosted on 2009-10-27 at 21:23:19ID: 25679922

You probably should go back to your initial code which seems to be ok beside that it deletes only one node (the node found) but not the requested number of following nodes.

Then you should add the number of nodes to delete after finding the initial node as an argument:

template <class Type>
void unorderedLinkedList<Type>::deleteNode(const Type& deleteItem, int numNodesToDelete)
{
    if (numNodesToDelete < 1)    // nothing to do
    {
         cout << "numNodesToDelete should be 1 or greater" << endl;
         return;
    }
    ...
}


Then, you should use a little helper function which gets a node pointer as argument and the number of nodes to delete after and would return the node pointer the last of those nodes was linked to:

template <class Type>
nodeType<Type> *  unorderedLinkedList<Type>::deleteNodesFrom(nodeType<Type> * node, int numNodesToDelete)
{
     if (node == NULL) return NULL;
     nodeType<Type> * next = node->link;
     int count = 0;

     // put here a do while loop that would first set the next to node->link
     // and then delete the node and increment the counter
     // the loop would stop either if next is NULL or if the counter reached the number of nodes to delete

     do
     {
          ...
     }
     while (...);
     // finally return the next which points to the next node not deleted or NULL
     return next;
}

The function above could be used both for "case 2" where the first node of list needs to get deleted and for the "else" case where one of the middle nodes was the initial node to be deleted.

In "case 2" the pointer returned from above function would become the new first (and last if list now is empty or has one node only) or would be the pointer the previous before the found node (trailCurrent) would link to.

 

by: Infinity08Posted on 2009-10-28 at 00:04:21ID: 25680543

>> I dont see how trailCurrent is used after it has been deleted by current

Ok. Drawing time ...

This is the linked list before the while loop :

                    -----      -----       -----      -----      -----
        first--->| 1 |--->| 2 |--->| 3 |--->| 4 |--->| 5 |--->NULL
                    -----      -----       -----      -----      -----

We want to delete the node 3 (and those after it), so after the while loop, 'current' points to that node, and 'trailCurrent' points to the node before it :

                    -----      -----       -----      -----      -----
        first--->| 1 |--->| 2 |--->| 3 |--->| 4 |--->| 5 |--->NULL
                    -----      -----       -----      -----      -----
                                  /\           /\
                                   |            |
                       trailCurrent    current

To delete node 3, we first "skip" it :
                                     ____________
                                    /                      \/
                    -----      -----       -----      -----      -----
        first--->| 1 |--->| 2 |      | 3 |--->| 4 |--->| 5 |--->NULL
                    -----      -----       -----      -----      -----
                                  /\           /\
                                   |            |
                       trailCurrent    current

Then we delete the node :

                                     ____________
                                    /                      \/
                    -----      -----                    -----      -----
        first--->| 1 |--->| 2 |                   | 4 |--->| 5 |--->NULL
                    -----      -----       NULL     -----      -----
                                  /\           /\
                                   |            |
                       trailCurrent    current

'current' now no longer points to an existing node, so we let it point to the next node we want to delete :

                                     ____________
                                    /                      \/
                    -----      -----                    -----      -----
        first--->| 1 |--->| 2 |                   | 4 |--->| 5 |--->NULL
                    -----      -----                    -----      -----
                                  /\                        /\
                                   |                         |
                       trailCurrent                current

So, this time we can delete node 4 in exactly the same way.

Go over these drawings and explanations, and please ask if anything is not clear. As long as you don't understand what's happening, and why, you will not be able to correctly implement this.

First understand it, then write the code.

 

by: StealthrtPosted on 2009-10-28 at 14:41:01ID: 25688640

Well using your examples Infinity08:

                    -----      -----       -----      -----      -----
        first--->| 1 |--->| 2 |--->| 3 |--->| 4 |--->| 5 |--->NULL
                    -----      -----       -----      -----      -----
                      /\           /\
                      |            |
       trailCurrent    current

Thats what i am trying to do. Where is current = "barker" and trailCurrent = "bob"

I need to start from "bob" and delete down the list til say, the 5th node. Right now, its skipping the node after "barker".

This is how i am reading this code:

found = false; // set to false
trailCurrent = first; // put "bob" into trailCurrent
current = first->link; // set current = to "barker"

while (current != NULL && !found) // make sure there is nodes
{
if (current->info != deleteItem) //check to see if current = "barker"
{
trailCurrent = current; // if so then set "barker" to trailCurrent
current = current-> link; // set current to whatever node is after "barker"
}else
{
found = true; // set it to true
}

if (found)
{
trailCurrent->link = current->link; // set trailCurrent = to current "baker"
count--; // count minus current count

if (last == current) // check to see if "barker" is the last in the node
{
last = trailCurrent; // if it is then set it to last
}

current = first; // I do not know what this does.. would this be "bob"?
first = first->link; // if its "bob" above then this must be "barker"
trailCurrent = first; // sets trailCurrent to "barker" if code above is correct

if (first == NULL) // check to see if first is null
last = NULL; // if so then last must be null
                       
delete current; // delete "bob"

tmp = first->link; // set tmp to "barker"
first->link = first->link->link; // set first to whatever comes next after "barker"
delete tmp; // delete "barker"

etc etc...

David

 

by: Infinity08Posted on 2009-10-28 at 15:46:22ID: 25689076

>> I need to start from "bob" and delete down the list til say, the 5th node.

You're starting off all wrong.

If you want to start deleting from the first node, then that's a special case.

Either way, 'current' should point to the first node (because that's the first node you want to delete).

Instead of starting with a special case, try starting with the basic case - ie. the one I showed. Once you get that to work, you can work on the special cases (involving the start and end of the linked list).

 

by: StealthrtPosted on 2009-11-07 at 12:58:25ID: 25768003

Alright, i've been working on it and still am not getting anywhere.

David

 

by: itsmeandnobodyelsePosted on 2009-11-08 at 02:06:26ID: 25769988

>>>> Alright, i've been working on it and still am not getting anywhere.
What do you expect us to do?

Is it really so difficult to not deleting the *current* but the node after the current and link the current with the next after the node to delete?

  current         current->link     current->link->link
   [1]       ->       [2]             ->         [3]


deleting [2] ==>

   [1]      ->     [3]


If you understand that, is it really so difficult to find out that in case you want to delete the very first node, you have a special situation as there is no current which can point to the node you want to delete.

  root         root->link              root->link->link
   [1]       ->       [2]             ->         [3]


So, when deleting [1] you will get a new root and have

    [2]          ->         [3]

where [2] is the new root.



   

 

by: Infinity08Posted on 2009-11-08 at 02:18:11ID: 25770022

Can you just start over, and write new code ?

Create a linked list with 5 nodes, just like in my earlier post http:#25680543.

Then try deleting node 3, just like I showed.

Once that works, try expanding the code to delete both nodes 3 and 4.

Once that works, try the same with a bigger list, and try deleting 2 nodes starting from anywhere in the linked list (make sure to handle the start of the list as a special case).

Once that works, try the same, but this time let the user specify how many nodes need to be deleted starting from where.

Step by step, you'll get there. But start with the simple part.

 

by: StealthrtPosted on 2009-11-29 at 17:49:50ID: 31643143

Thanks for the help.

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...