Deleting the nth node in a list

So im having the problem of not knowing how to figure this out. I cant seem to find what i is equal to in the attached pre-coded programs so im assuming they set it to the nth node they wanted deleted which is 3. my problem i think is my first while loop as its not actually exiting it when i set j!=i although, it will work with input data that has zero or only 3 data sets, anymore and itll not cout the edited list

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include "inlab6.h"
#include "structs.h"

#include <iostream>
#include <fstream>
#include <stdlib.h>
using namespace std;

//Function to delete the ith node from the list
//  If there are fewer than i nodes in the list, an error is returned.
void ListClass::deleteIthNode(int i)
{
    NodePtrType q = head; //q will point to the item to delete
    NodePtrType prev;           //prev will point to the item before q    
    int j = 1;            //j will keep count of which node in the list
                          //    we are currently on                   

    if (head == NULL)
        cout<<"Not enough items in list\n";
    else
    {
        //Traverse the list to find the ith item
    //    The following is a while loop that will traverse
    //    the list until either j == i or the end of the list
    //    is encountered.

//j==i will let second part of cout in main work
	while(j!=i||q->next!=NULL )
	{   //keep prev one behind q
		prev=q; 
		q=q->next;
		j++;



	}
  //If there are i items in the list, delete the ith one
    //    The following is the if part of an if-else statement.
    //    The if part should delete the ith item if there is an
    //    ith item.
	
	if (q->next== NULL)
	{
		
		prev->next=q->next;
		delete q;
		q=NULL;
	}

Last edited on
Not sure if it's your only problem, but in your while loop on line 28, it should be a &&, not ||. As you have it now, if you're looking for the 3rd element in a 5 element list, when it gets to j = 3, the first part of the condition will be false, but the second part will still be true because there are still more nodes in the list, and your loop will continue.
Last edited on
I tried using && and it gives me a compile error on the data file with only one set of numbers, and tells me theres not enough items in the list, for the one that has 4 sets of numbers. plus the instructions say "or". im not sure what else i would need to change to make && work
Last edited on
Anyone?
Topic archived. No new replies allowed.