Usuwanie k-tego elementu listy jednokierunkowej

0

Co jest źle w szablonie tej metody? Wyskakuje runtime error, prawdopodobnie gdzieś jest wyjście poza przydzieloną pamięć.

template <class Type>
void linkedListType<Type>::deleteParticularNode(int k) 
{
	nodeType<Type> *current,*temp;
	current=first;

	if(0>k || k>length())
	{
		cout<<"Incorrect node number entered!";
		return;
	}
	if(first==NULL)
	{
		cout<<"Cannot delete from an empty list\n";
		return;
	}

	for(int i=1; i<k-2 ; i++)
	current=current->link;

	temp=current;
	
	current->link=current->link->link;


	delete temp;

	temp=NULL;

	count--;
}
 

Błąd:

An unhandled exception of type 'System.AccessViolationException' occurred in linked_list_ADT.exe

Additional information: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

testowa funkcja main

// linked_list_ADT.cpp : main project file.

#include "stdafx.h"
#include <iostream>
#include <string>
#include "ordered_linked_list.h"


#define N 6

using namespace std;

int main()
{
	unorderedLinkedList<int> listOfIntegers;
	int tmp;

	for(int i=0;i<N;i++)
	{	
		cin>>tmp;
		listOfIntegers.insertLast(tmp);
	}

	listOfIntegers.print();

	cout<<endl;
	//cout<<listOfIntegers.getParticularInfo(3);

	
	cout<<endl;
	listOfIntegers.deleteParticularNode(3);
	
	listOfIntegers.print();
							


	cout<<endl;
	system("PAUSE");
    return 0;
}

 
1
  1. k>=length()
  2. if(first==NULL) - jak poprawisz punkt 1, to to nigdy nie bedzie spelnione
  3. powinenes rozpatrzyc usuwanie w dwoch wersjach: usuwanie pierwszego elementu i usuwanie jednego z pozostalych elementow
    4. zastanow sie co przechowuje current. wg. mnie przechowuje on element poprzedzajacy usuwany, a ty mimo tego ze o tym wiesz, bo zakladam ze kod sam pisales, to usuwasz element temp=current zamiast temp=current->link
  4. temp=NULL; - ustawianie zmiennej lokalnej na nulla przed koncem funkcji jest co najmniej bez sensu
  5. if(0>k || k>length()) - ten warunek jest strasznie nie czytelny, lepiej gdyby wygladal tak: if (!(k>=0 && k<length())) lub nawet tego nota wywalic i po prostu zamienic kolejnosc wykonywania blokow. jak juz sie koniecznie uprzesz przy swojej wersji to chociaz 0>k popraw na k<0, niby to samo ale latwiej sie to czyta (k mniejsze od 0, a nie 0 wieksze od k, które powoduje dłuższą chwilę zastanowienia)
0

Poprawiłem i działa

template <class Type>
void linkedListType<Type>::deleteParticularNode(int k) 
{
	nodeType<Type> *current,*temp;
	current=first;
	

	if(k<1 || k>length())
	{
		std::cout<<"Incorrect node number entered!";
		return;
	}

	if(first==NULL)
	{
		std::cout<<"Cannot delete from an empty list!";
		count--;
		return;
	}

	if(k==1)
	{
		current=first;
		first=first->link;
		
		delete current;
		return;
	}

	for(int i=1; i<k-1 ; i++)
	current=current->link;

	temp=current->link;

	current->link=current->link->link;

	delete temp;

	count--;
}

1 użytkowników online, w tym zalogowanych: 0, gości: 1