Below I have attached 4 methods from my linked list class.


1) find 2)remove 3)retrieve 4) Insert.

what I'm trying to do is write code that will let me MOVE the position of a node to another position in the linked list.

Anyone got a clue??

regards

Tim

SeqItemType Sequence::retrieve(int index)
  {
  
   	if ((index < 1) || (index > size())){
   		// can't delete something that isn't there
   	}
   	ListNode *cur = find(index);
    return cur->item;	
  } 



   void Sequence::insert(int index, SeqItemType newItem)
  {
   	
	if ((index < 1) || (index > (size()+1))){
   		// if index is out of bounds don't do anything
   	}
   	else
   	{  
   		// otherwise create new node and place newItem in it
      	ListNode *newPtr = new ListNode();
      	
      	// increment the size attribute
      	length++;
        // store the data item in the new node
      	newPtr->item = newItem;

		//  if the index is 1, insert new node at beginning of list
        if (index == 1)
        { 
       		newPtr->next = head;
        	head = newPtr;
        }
        else
        {  
        	ListNode *prev = find(index-1);
        	newPtr->next = prev->next;
			prev->next = newPtr;
            
        }
	 } 
   }


void Sequence::remove(int index) 
{   
    
	ListNode *cur;

   	if ((index < 1) || (index > size())){
   	
   		}
   	else
   	{  
		// remove the first node in the list
		if (index == 1)
      	{ 
      		cur = head;
     		head = head->next;   	
     		
      	}
		else{
        	ListNode *prev = find(index-1);	
        		
			cur = prev->next;
			prev->next = cur->next;
		}	
		
		// clean things up!
		length--;
		cur->next = NULL;
		delete cur;
	}
  
}


ListNode *Sequence::find(int index){

	if ((index <1) || (index >size())){
		return 0;
	}
	else{
		ListNode *cur = head;
		for(int skip =1; skip<index; ++skip)
			cur=cur->next;
		return cur;
  	}
}

Ok, I cant handle it. my head is wrecked from trying out but miserably failing with new code. Has anyone got a clue where to go from here. Can some take pity on this man....after all its christams :)

What is wrong with using the functions you already got

void Sequence::move(int from, int to)
{
  SeqItemType item = find( from )->item ;
  remove(from) ;
  insert( to, item ) ;
}

Perfect, solution.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.