Janet D
Janet D

Reputation: 43

Linked List remove item

Ive got to remove an item from my list using the 'RemoveItem' method. However, im a little stuck, can anyone give me a prod in the right direction :D

any help would be highly appreciated

main:

class Program
{
    static void Main(string[] args)
    {
        LinkList testList = new LinkList();

        testList.AddItem(5);
        testList.AddItem(10);
        testList.AddItem(12);
        testList.AddItem(14);
        testList.DisplayItems();
        Console.WriteLine(testlist.RemoveItem(5));/// remove the item 5 from list

        Console.ReadKey();
    }
}

link class:

class Link
{
    private int data;
    private Link next;

    public Link(int item) //constructor with an item
    {
        data = item;
        next = null;
    }
    public Link(int item, Link list) //constructor with item and list
    {
        data = item;
        next = list;
    }

    public int Data //property for data
    {
        set { this.data = value; }
        get { return this.data; }
    }

    public Link Next //property for next
    {
        set { this.next = value; }
        get { return this.next; }
    }

  }
}

linklist class:

 class LinkList
    {
        private Link list = null; //default value – empty list

        public void AddItem(int item) //add item to front of list
        {
            list = new Link(item, list);
        }

        public void RemoveItem(int item)// remove chosen item from list
        {
            Link temp = list;
            while (temp != null)
            {
               //
            }

        public void DisplayItems() // Displays items in list
        {
        Link temp = list;
        while (temp != null)
        {
            Console.WriteLine(temp.Data);
            temp = temp.Next;
        }

    }

Upvotes: 0

Views: 200

Answers (1)

Artem E
Artem E

Reputation: 367

There are two ways:

  • To take value and delete it
  • Just delete it

First decide what you need.

Describe idea with words for yourself. What does it mean to delete item?

  • find item
  • delete item
  • correct links: item before deleted item have to be linked with item after deleted

Example

A->B->C->D->E

Delete C: find C, make link between B and D to get

A->B->D->E

Before trying to connect nodes, first check if they exists :)

Upvotes: 2

Related Questions