Click here to Skip to main content
15,892,809 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
C++
#include <iostream>

using namespace std;

//Linked List: Delete a node at nth position

struct Node {
	int data;
	Node* next;
};

Node* head; //Global

void Insert(int data) { //Insert an integer at the end of list
	Node* temp1 = new Node;
	temp1->data = data;
	temp1->next = head;
	head = temp1;
}

void Print() { //Print all elements in the list
	Node* temp1 = head;
	while (temp1 != NULL) {
		cout << " " << temp1->data;
		temp1 = temp1->next;
	}
	cout << endl;
}

void Delete(int n) { //Delete node at position n
	Node* temp1 = head;
	if (n == 1) {
		head = temp1->next; //head now points to second node
		delete temp1;
		return;
	}
	for (int i = 0; i < n - 2; i++)
		temp1 = temp1->next; //temp1 points to (n - 1)th Node
	Node* temp2 = temp1->next; //nth Node
	temp1->next = temp2->next; // (n + 1)th Node
	delete temp2;

}


What I have tried:

int main() {

    head = NULL; //Empty list
    while(cin>>num)
{
Insert(num);
}
  
    Print();
    int n;
    cout << "Enter a position" << endl;
    cin >> n;
    Delete(n);
    Print();
    return 0;
}


Here in the main function I'm trying to enter elements from the keyboard(with while loop) in the linked list. The problem is that when I add elements the program automatically deletes the second element and don't let me to enter n.
Here's what I mean:
http://oi68.tinypic.com/v6nno2.jpg
Notice that I enter letter to stop the loop.
Posted
Updated 5-May-16 6:51am
v2

1 solution

You should learn to use the debugger as soon as possible. Rather than guessing what your code is doing, It is time to see your code executing and ensuring that it does what you expect.

The debugger allow you to follow the execution line by line, inspect variables and you will see that there is a point where it stop doing what you expect.
Debugger - Wikipedia, the free encyclopedia[^]
Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]

When you delete a node, you forget to check if node exist.
Use the debugger to see where your code goes wrong.
 
Share this answer
 
Comments
shihappns 5-May-16 12:56pm    
I forgot to add the loop. Now you can see it. I don't know why after the first call of function Print() the program doesn't allow me to enter n. Just automaticly deletes the second element.
Patrice T 5-May-16 13:11pm    
use the debugger
shihappns 5-May-16 15:10pm    
I used break points but this didn't help me to figure out what is missing.
Patrice T 5-May-16 15:21pm    
put a breakpoint at first line of delete, then execute line by line and inspect extensively the variables, be attentivr to what append when you change the list.
Note address of each node as you build list.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900