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

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




Overloading comparison operators in a Linked List

 
Reply to this topicStart new topic

Overloading comparison operators in a Linked List, >, <, >=, <=

CrazyJ
12 Nov, 2007 - 03:01 PM
Post #1

D.I.C Head
**

Joined: 15 Oct, 2007
Posts: 51


My Contributions
I am implementing a linked list with a menu whereupon I am overloading the following operators:
+
-
>
<
<=
>=
==
!=
I have the sum and difference done but I am having trouble with the comparison operators. I am getting conflicts with the bool type, I am including the code from the class where I am having trouble. The problem begins where I am implementing the > operator. Thanks in advance for any advice! icon_up.gif
CODE

using System;
using System.Collections.Generic;
using System.Text;

namespace SinglyLinkedListProject
{
    public class SinglyLinkedList
    {
//  =================================
//  Data fields (instance variables):
//  =================================

//      ===================
        private Node first;
//      ===================

//      ===================================================
//      Allowing a last node reference makes it possible to
//      implement a SinglyLinkedList operator than can add
//      a node to the end of a SinglyLinkedList instance without
//      forcing the method to traverse the entire list.
        private Node last;
//      ==================

//      ========================
        private string listName;
//      ========================

//  =============
//  Constructors:
//  =============

//      =============================
//      Constructor SinglyLinkedList:
//      ============================================
        public SinglyLinkedList( string nameOfList )
        {
            first = null;
            last  = null;
            listName = nameOfList;
        } // constructor SinglyLinkedList
//      =================================

//  ==============================
//  Interface Operators (Methods):
//  ==============================

//      ===========================
//      SinglyLinkedList operators:
//
//      + (Overload for the addition of two lists.)
//      - (Overload for the subtracttion of two lists.)
//        (Overload for the following for list comparisons.)
//      >
//      <
//      <=
//      >=
//      ==
//      !=
//
//      ----------------------------------------------
//      Unlike C++, the assignment operator, =, cannot
//      be overloaded in C#.  Thus, a DeepCopy interface
//      method can take the place of an overloaded
//      assignment operator.

//      DeepCopy( list );
//      -----------------

//      DeleteFirst();              Overloaded
//      DeleteFirst( datum );       Overloaded
//      DeleteLast();
//      DeleteNode( int );
//      DestroyList();              Not needed with the garbage collector
//      InitializeList();           Not needed, as the constructor initializes the list.
//      InsertFirst( datum );
//      InsertLast( datum );
//      IsEmpty();
//      Length();
//      ObtainFirst( out datum );
//      ObtainLast( out datum );
//      Print();
//      Search( itemToFind, out nodeLocation );
//      ShallowCopy( list );       Not needed, as the assignment, =, operator does this.
//      ====================

//  =====================
//  Overloaded Operators:
//  =====================


//      ==================================================================
        public static SinglyLinkedList operator +( SinglyLinkedList listA,
                                                   SinglyLinkedList listB )
        {
            SinglyLinkedList sum = new SinglyLinkedList("sum");

            Node handleListA = listA.first;
            Node handleListB = listB.first;

            while ( (handleListA != null) && (handleListB != null) )
            {                                                          
                sum.InsertLast(handleListA.datum + handleListB.datum);                        
                handleListA = handleListA.next;
                handleListB = handleListB.next;
            } // while

            return sum;  
        } // operator +
//      ===============

//      =======================================================
        public static SinglyLinkedList operator -( SinglyLinkedList listA,
                                                  SinglyLinkedList listB )
        {
            SinglyLinkedList difference = new SinglyLinkedList("difference");

            Node handleListA = listA.first;
            Node handleListB = listB.first;

            while ((handleListA != null) && (handleListB != null))
            {
                difference.InsertLast(handleListA.datum - handleListB.datum);
                handleListA = handleListA.next;
                handleListB = handleListB.next;
            } // while

            return difference;
        } // operator -
//      ================

//      =================================================================
//          The overloaded operator > returns true if the number of nodes
//      in listA exceeds the number of nodes in listB; else it
//      returns false.
//          Also note that the implementation of the > operator requires
//      the implementation of the < operator, or the compiler will emit
//      a syntax error.
//      =======================================================
        public static bool operator >(SinglyLinkedList listA,
                                        SinglyLinkedList listB)
        {
            SinglyLinkedList greaterThan = new SinglyLinkedList("greater than");

            Node handleListA = listA.first;
            Node handleListB = listB.first;

            while ((handleListA != null) && (handleListB != null))
            {
                greaterThan.InsertLast(handleListA.datum > handleListB.datum);
                handleListA = handleListA.next;
                handleListB = handleListB.next;
            } // while

            return greaterThan;  
            //return listA.Length() > listB.Length();
        } // operator >
//      ===============

//      =================================================================
//          The overloaded operator < returns true if the number of nodes
//      in listA is less than the number of nodes in listB; else it
//      returns false.
//          Also note that the implementation of the < operator requires
//      the implementation of the > operator, or the compiler will emit
//      a syntax error.
//      =======================================================
        public static bool operator < ( SinglyLinkedList listA,
                                        SinglyLinkedList listB)
        {
            return listA.Length() < listB.Length();
        } // operator >
//      ===============

//      ==================================================================
//          The overloaded operator == returns true if the number of nodes
//      in listA is equal to the number of nodes in listB; else it
//      returns false.  This implementation of the == operator only
//      considers two lists equal if they contain the same number of nodes.
//      Equality does not depend upon the list being both equal in node
//      count as well as equal in quantity.
//          Also note that the implementation of the == operator requires
//      the implementation of the != operator, or the compiler will emit
//      a syntax error.
//      =======================================================
        public static bool operator ==( SinglyLinkedList listA,
                                        SinglyLinkedList listB )
        {
            return listA.Length() == listB.Length();
        } // operator ==
//      ================

//      ==================================================================
//          The overloaded operator != returns true if the number of nodes
//      in listA is not equal to the number of nodes in listB; else it
//      returns false.  
//          Also note that the implementation of the != operator requires
//      the implementation of the == operator, or the compiler will emit
//      a syntax error.
//      =======================================================
        public static bool operator !=( SinglyLinkedList listA,
                                        SinglyLinkedList listB)
        {
            return !(listA == listB);
        } // operator !=
//      ================

//      =======================================================
        public static bool operator >=( SinglyLinkedList listA,
                                        SinglyLinkedList listB )
        {
            return listA.Length() >= listB.Length();
        } // operator >=
//      ================

//      =======================================================
        public static bool operator <=( SinglyLinkedList listA,
                                        SinglyLinkedList listB )
        {
            return listA.Length() <= listB.Length();
        } // operator <=
//      ================

//      ===============================================================
//          Also, overriding the == operator will cause the compiler to
//      emit a warning about the need to override the Object.Equals(objct o)
//      method. Some .NET programming languages do not allow operators
//      to be overloaded, so an Equals method is needed for language
//      interaction.
//      =========================================
        public override bool Equals( object obj )
        {
            if (!(obj is SinglyLinkedList))
                return false;

            return this == (SinglyLinkedList)obj;
        } // method Equals
//      ==================

//      ===============================================================
//          Also, overriding the == operator will cause the compiler to
//      emit a warning about the need to override the Object.GetHashCode()
//      method.  A hash method outputs a hashcode, which basically provides
//      a value for a given object.  When a hash code is assigned to an
//      object, this makes it possible for a program to more efficiently
//      store an object in a collection.  GetHashCode uses the list length
//      as a hash code value.
//          Also, note that the Length() method returns a long value, but
//      the hash code is an int.  Thus, a cast is performed here.
//      ==================================
        public override int GetHashCode( )
        {
            return (int)this.Length();
        } // GetHashCode
//      ================

//  ========
//  Methods:
//  ========

//      ================
//      Method DeepCopy:
//      ===================================================
        public void DeepCopy(SinglyLinkedList originalList)
        {            
            Node originalListReference;
            SinglyLinkedList newList = new SinglyLinkedList("newList");
        
            originalListReference = originalList.first;
            while ( originalListReference != null )
            {
                newList.InsertLast(originalListReference.datum);
                originalListReference = originalListReference.next;                                
            } // while

            first = newList.first;
            last = newList.last;
        } // method DeepCopy
//      ====================

//      =================================================================
//          The member function DeleteFirst() deletes the first node from
//      a singly linked list.  If the list is empty, then DeleteFirst()
//      leaves the list as is.  This version of DeleteFirst does not return
//      the datum held by the node.
//          Also, remember the runtime environment provides a garbage
//      collector, so DeleteFirst does not actually deallocate the space
//      used by the first node, but simply removes the program's reference
//      to that node so that the garbage collector can deallocate the space
//      when ready to do so.
//      ==========================
        public void DeleteFirst( )
        {
            if (Length() >= 1){

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

            } // if then            
        } // DeleteFirst
//      ================

//      =====================================================================
//      The method  InsertFirst creates a new node, assigns the value held by
//      the parameter value to the node datum element, and places this new node
//      at the beginning of a singly linked list.  That is, if the list is empty,
//      then the newNode becomes the first and only node in the list.  If
//      the list is not empty, then newNode becomes the first of many nodes.
//      ====================================
        public void InsertFirst( int value )
        {            
            if ( first == null ) {
                Node newNode = new Node(value, null);
                first = newNode;
                last = first;
            }
            else {
                Node newNode = new Node(value, first);
                first = newNode;
            } // else
        } // InsertFirst
//      ================

//      =====================================================================
//      The method  InsertLast creates a new node, assigns the value held by
//      the parameter value to the node datum element, and places this new node
//      at the end of a singly linked list.  That is, if the list is empty,
//      then the newNode becomes the first and only node in the list.  If
//      the list is not empty, then newNode becomes the last of one or more nodes.
//      ===================================
        public void InsertLast( int value )
        {                
            Node newNode = new Node(value, null);

            if ( first == null ) {                
                first = newNode;
                last = first;
            }
            else {
                last.next = newNode;
                last = newNode;
            } // else
        } // InsertLast
//      ===============

//      ===============
//      Method IsEmpty:
//      ======================
        public bool IsEmpty( )
        {
            return (first == null);
        } // IsEmpty
//      ============

//      ==========================================================
//      The method Length returns the length of the invoking list.
//      =====================
        public long Length( )
        {

        long nodeCounter;
        Node current;

        nodeCounter = 0;
        current = first;
        while ( current != null ) {
            nodeCounter++;
            current = current.next;
        } // while
  
        return nodeCounter;

        } // method Length
//      ==================

//      =================================================================
//      The method Print allows an instance of the SinglyLinkedList class
//      to write to standard output information concerning its content.
//      ===================
        public void Print()
        {
            Node newNode;

            Console.WriteLine();
            Console.WriteLine("===========");
            Console.WriteLine("List: " + listName);
            Console.WriteLine();

            newNode = this.first;
            while (newNode != null)
            {
                Console.Write(newNode.datum + " ");
                newNode = newNode.next;
            } // while

            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine("Method Print terminating.");
            Console.WriteLine("=========================");

        } // method Print
//      =================

    } // class SinglyLinkedList
//  ===========================

} // namespace SinglyLinkedListProject
    

User is offlineProfile CardPM
+Quote Post

skaoth
RE: Overloading Comparison Operators In A Linked List
12 Nov, 2007 - 06:46 PM
Post #2

D.I.C Regular
Group Icon

Joined: 7 Nov, 2007
Posts: 342



Thanked: 10 times
Dream Kudos: 100
My Contributions
The simple answer is that you are returning the wrong type.
The overloaded function requires that you return a bool.
the function is acutally returning an object of type SinglyLinkedList.

CODE

public static bool operator >(SinglyLinkedList listA,
                                        SinglyLinkedList listB)
        {
            SinglyLinkedList greaterThan = new SinglyLinkedList("greater than");

            Node handleListA = listA.first;
            Node handleListB = listB.first;

            while ((handleListA != null) && (handleListB != null))
            {
                greaterThan.InsertLast(handleListA.datum > handleListB.datum);
                handleListA = handleListA.next;
                handleListB = handleListB.next;
            } // while

            return greaterThan;  
            //return listA.Length() > listB.Length();
        } // operator >

User is online!Profile CardPM
+Quote Post

CrazyJ
RE: Overloading Comparison Operators In A Linked List
12 Nov, 2007 - 07:19 PM
Post #3

D.I.C Head
**

Joined: 15 Oct, 2007
Posts: 51


My Contributions
I actually found a better method to do this, but now I have another issue that is dogging me. I set it up to compare like this:
CODE

//      =======================================================
        public static bool operator >(SinglyLinkedList listA,
                                        SinglyLinkedList listB)
        {
            return listA.Length() > listB.Length();
        } // operator >
//      ===============


and then I am implementing it in a menu like so:
CODE

case 14:
                        if (listA < listB)
                            Console.WriteLine("ListB is larger than ListA");
                        else Console.WriteLine("ListA is larger than ListB");
                        break;


But, when I enter values in for ListA and ListB, it gives me "ListA is larger than ListB" no matter what. Even when ListB is much larger...
???
User is offlineProfile CardPM
+Quote Post

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

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