Welcome to Dream.In.Code
Getting C# Help is Easy!

Join 136,100 C# Programmers for FREE! Get instant access to thousands of C# experts, tutorials, code snippets, and more! There are 1,653 people online right now. Registration is fast and FREE... Join Now!




Delete element method in Linked List

 
Reply to this topicStart new topic

Delete element method in Linked List, Need to delete element in "last" node

CrazyJ
14 Nov, 2007 - 10:05 PM
Post #1

D.I.C Head
**

Joined: 15 Oct, 2007
Posts: 51


My Contributions
Hi, I have this linked list in C# whereupon I am overloading binary operators based on int input from the user, as well as manipulating the list using a menu whinch allows the user to choose which operators to use. My issue right now is in my "DeleteLast" method. I need to enable the deletion of the last node element if so chosen. My "DeleteFirst" method works just fine, deleting an element each time the user chooses the DeleteFirst menu option. If anyone can take a peek at my gob of code and tell me what I'm doing wrong in this particular method, it would really be appreciated. Thanks!

This is just the portion of my class where I am having the issue with DeleteLast...
CODE

//      ==========================
        public void DeleteFirst( )
        {
            if (Length() >= 1){

                if (Length() == 1){
                    first = null;
                    last = null;
                }
                else { // Length() > 1
                    first = first.next;
                } // else

            } // if then            
        } // DeleteFirst
//      ========================
        public void DeleteLast()
        {
            if (Length() >= 1)
            {

                if (Length() == 1)
                {
                    first = null;
                    last = null;
                }
                else
                { // Length() > 1
                    last = last.next;
                } // else

            }//if then
        }//DeleteLast


and my Node class

CODE

   public class Node
    {

//      ====================
        internal int  datum;
        internal Node next;
      
//      ===================
        
//  =============
//  Constructors:
//  =============

//      ============
//      Constructor:
//      ==============================
        public Node( int  nodeElement,
                     Node n )
        {
            datum = nodeElement;
            next = n;
        } // constructor Node
//      =====================

    } // class Node
//  ===============


the MainProgram

CODE

class MainProgram
    {
        
//      ===============================
        static void Main(string[] args)
        {
            int  menuNumber;
            int  datumValue;

            bool goAgain = true;

            SinglyLinkedList listA = new SinglyLinkedList("listA");
            SinglyLinkedList listB = new SinglyLinkedList("listB");
            SinglyLinkedList listC = new SinglyLinkedList("listC");

//          ===============
            do // User loop
            {
                UtilityMethods.Menu( out menuNumber );
              
//              =====================
                switch ( menuNumber )
                {
                    case 1:
                        UtilityMethods.CaseBanner("Initialize ListA.");
                        listA = new SinglyLinkedList("listA");
                        break;

                    case 2:
                        UtilityMethods.CaseBanner("Initialize ListB.");
                        listB = new SinglyLinkedList("listB");
                        break;

                    case 3:
                        UtilityMethods.CaseBanner("Output ListA.");
                        listA.Print();
                        break;

                    case 4:
                        UtilityMethods.CaseBanner("Output ListB.");
                        listB.Print();
                        break;

                    case 5:
                        UtilityMethods.CaseBanner("Output ListC.");
                        listC.Print();
                        break;

                    case 6:
                        UtilityMethods.CaseBanner("Insert First ListA.");
                        UtilityMethods.GetInteger( out datumValue );
                        listA.InsertFirst( datumValue );
                        break;

                    case 7:
                        UtilityMethods.CaseBanner("Delete First ListA.");
                        listA.DeleteFirst();
                        break;

                    case 8:
                        UtilityMethods.CaseBanner("Insert First ListB.");
                        UtilityMethods.GetInteger(out datumValue);
                        listB.InsertFirst( datumValue );
                        break;

                    case 9:
                        UtilityMethods.CaseBanner("Delete First ListB.");
                        listB.DeleteFirst();
                        break;

                    case 10:
                        UtilityMethods.CaseBanner("Insert Last ListA.");
                        UtilityMethods.GetInteger( out datumValue );
                        listA.InsertLast(datumValue);
                        break;

                    case 11:
                        UtilityMethods.CaseBanner("Delete Last ListA.");
                        listA.DeleteLast();
                        break;


                    case 12:
                        UtilityMethods.CaseBanner("Insert Last ListB.");
                        UtilityMethods.GetInteger(out datumValue);
                        listB.InsertLast( datumValue );
                        break;

                    case 13:
                        UtilityMethods.CaseBanner("Delete Last ListB.");
                        listB.DeleteLast();
                        break;

                    case 14:
                        UtilityMethods.CaseBanner("Deep Copy ListA to ListB.");
                        listB.DeepCopy(listA);
                        break;

                    case 15:
                        UtilityMethods.CaseBanner("Deep Copy ListB to ListA.");
                        listA.DeepCopy(listB);
                        break;

                    case 16:
                        UtilityMethods.CaseBanner("ListC = ListA + ListB.");
                        listC = new SinglyLinkedList("listC");
                        listC = listA + listB;
                        break;

                    case 17:
                        UtilityMethods.CaseBanner("ListC = ListA - ListB.");
                        listC = new SinglyLinkedList("listC");
                        listC = listA - listB;
                        break;

                    case 18:
                        if (listA > listB)
                        {
                            Console.WriteLine("ListA is larger than ListB");
                        }
                        else if (listA < listB)
                        {
                            Console.WriteLine("ListB is larger than ListA");
                        }
                            
                        else
                        {
                            Console.WriteLine("ListA and ListB must be equal.");
                        }  
                        break;

                    case 19:
                        if (listA == listB)
                        {
                            Console.WriteLine("ListA and ListB are equal length.");
                        }
                        else
                        {
                            Console.WriteLine("ListA and ListB are not equal length.");
                        }
                        break;

                    case 20:
                        if (listA >= listB)
                        {
                            Console.WriteLine("ListA is greater than or equal to ListB.");
                        }
                        else if (listA <= listB)
                        {
                            Console.WriteLine("ListA is less than or equal to ListB.");
                        }

                        else
                        {
                            Console.WriteLine("ListA and ListB must be equal.");
                        }  
                        break;

                    case 21:
                        UtilityMethods.CaseBanner("Exit Program.");
                        goAgain = false;
                        break;


                    default:                          
                        Console.WriteLine("Invalid menu item.");
                        break;
                            
                } // switch
//              ===========

            } while ( goAgain );
//          ====================
            
        } // method Main
//      ================

    } // class MainProgram
//  ======================

} // namespace SinglyLinkedListProject


Thanks so much for any advice biggrin.gif

User is offlineProfile CardPM
+Quote Post

Martyr2
RE: Delete Element Method In Linked List
15 Nov, 2007 - 10:55 AM
Post #2

Programming Theoretician
Group Icon

Joined: 18 Apr, 2007
Posts: 5,198



Thanked: 213 times
Expert In: C/C++, Java, VB, VB.NET, C#, PHP, Web Development, HTML & CSS, Javascript

My Contributions
I am going to take a stab at this since I am not completely sure what first and last may exactly mean. But I think the problem is with your statement last = last.next. First thing I want to point out is that if this is the last node, last.next will be null. Which is fine, but I wanted to make sure you knew that. What you need to do is get the reference to the node BEFORE the last and set its "next" to last.next. The idea is that the node before the node to be deleted will have to have its "next" pointer point to the one AFTER the node being deleted. In this case again, it will be null if this is the last element. So navigate to the node before the last node, lets call it secondtoLast and set it up like...

CODE

secondtoLast.next = last.next;


The image of this would look like so....

IPB Image

Hope that clarifies some things.

Enjoy!

"At DIC we be node changing code ninjas!" decap.gif

User is online!Profile CardPM
+Quote Post

baavgai
RE: Delete Element Method In Linked List
15 Nov, 2007 - 01:14 PM
Post #3

Dreaming Coder
Group Icon

Joined: 16 Oct, 2007
Posts: 2,019



Thanked: 105 times
Dream Kudos: 475
Expert In: C, C++, Java, C#, ASP.NET, PHP, Perl, Python, Oracle, SQL Server, MySql, HTML, JavaScript, Lua

My Contributions
I have to ask, you have to implement DeleteFirst and DeleteLast? Are you sure this is supposed to be a singly linked list? Why would be delete it from both ends?

Anyway, Martyr2's description is great. If you have a Length() function that works, it presumablely traverses all the next nodes? With the same code, have it hang on to the prior node and have the prior node ophan it's next when you get to the bottom.

Note, you absolutely should not have to check a Length() function for either of these opperations. e.g. DeleteFirst is as simple as if(first!=null) { first=first.next; }

Hope this helps.

User is offlineProfile CardPM
+Quote Post

CrazyJ
RE: Delete Element Method In Linked List
19 Nov, 2007 - 11:09 PM
Post #4

D.I.C Head
**

Joined: 15 Oct, 2007
Posts: 51


My Contributions
QUOTE(Martyr2 @ 15 Nov, 2007 - 11:55 AM) *

I am going to take a stab at this since I am not completely sure what first and last may exactly mean. But I think the problem is with your statement last = last.next. First thing I want to point out is that if this is the last node, last.next will be null. Which is fine, but I wanted to make sure you knew that. What you need to do is get the reference to the node BEFORE the last and set its "next" to last.next. The idea is that the node before the node to be deleted will have to have its "next" pointer point to the one AFTER the node being deleted. In this case again, it will be null if this is the last element. So navigate to the node before the last node, lets call it secondtoLast and set it up like...

CODE

secondtoLast.next = last.next;


The image of this would look like so....

IPB Image

Hope that clarifies some things.

Enjoy!

"At DIC we be node changing code ninjas!" decap.gif


Thanks Martyr2, that is a superb explanation of the way the next operator works. I actually got it figured out later on that morning so thanks are in order for all who replied...Thanks! I have another question though on the same program. I am trying to implement a "Search" operator that will iterate through the list and output the value in a given node based on input e.g. user types 5 and the program displays the value(element) in 5. I am having a problem calling it from my Main program. Also, shown below is code for an ObtainFirst and ObtainLast operators that will display elements in the first and last nodes, similar issue. Any suggestions?

Search, ObtainFirst & ObtainLast Methods:
CODE

public void Search(SinglyLinkedList list,
                           int nodeVal,
                           ref int nodeLocation)
        {

            int counter = 1;

            Node current;

            current = list.first;

            while (current != null)
            {

                if (current.datum == nodeVal)
                {

                    nodeLocation = counter;

                }

                current = current.next;

                counter++;

            }// while loop

        }//method Search
/      ===============
//      Method ObtainFirst:
//      ========================================
        public void ObtainFirst(ref int nodeVal)
        {
            nodeVal = first.datum;
        }//method ObtainFirst
//      =====================
//      Method ObtainLast:
//      ========================================
        public void ObtainLast(ref int nodeVal)
        {
            nodeVal = last.datum;
        }//method ObtainLast
//      ====================


Main program (where I am trying to call them):
CODE

case 14:
                        UtilityMethods.CaseBanner("ObtainFirst.");
                        UtilityMethods.GetInteger(out nodeVal);
                        listA.ObtainFirst(ref nodeVal);   //   <------Issue here?
                        break;

                    case 15:
                        UtilityMethods.CaseBanner("ObtainLast.");
                        UtilityMethods.GetInteger(out nodeVal);
                        listA.ObtainLast(ref nodeVal);   //   <-------
                        break;

//                    =====================
case 24:
                        UtilityMethods.CaseBanner("Search List.");
                        UtilityMethods.GetInteger(out nodeVal);
                        listA.Search();  //        <--------     <------What do I need to put here?
                        break;



The GetInteger Utility:
CODE

//      ================================================
        public static void GetInteger(out int intValue )
        {
            string intString;

            Console.WriteLine();
            Console.WriteLine("=======================");
            Console.WriteLine("Enter an integer value.");

            intString = Console.ReadLine();
            intValue = int.Parse(intString);

            Console.WriteLine("GetInteger terminating.");
            Console.WriteLine("=======================");
            Console.WriteLine();

        } // method IterateAgain
//      ========================

I hope this is sufficient, I didn't want to include ALL of the code again rolleyes.gif Thanks!
User is offlineProfile CardPM
+Quote Post

CrazyJ
RE: Delete Element Method In Linked List
20 Nov, 2007 - 10:45 AM
Post #5

D.I.C Head
**

Joined: 15 Oct, 2007
Posts: 51


My Contributions
I've got this one all wrapped up now icon_up.gif . Thanks alot Martyr2 and baavgai for your help. I appreciate your objective view, and thought provoking suggestions. Thanks.

"node changing code ninjas..." LOL... biggrin.gif
User is offlineProfile CardPM
+Quote Post

Fast ReplyReply to this topicStart new topic
Time is now: 12/1/08 08:47PM

Live C# Help!

C# Tutorials

Reference Sheets

C# Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month