linked lists problem

Hey, i made a linked list contain 4 nodes and i want to delete the second half of the linked list >> it dose not work with me

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
51
52
53
 #include<iostream>
using namespace std;
struct node{
	int data;
	node *next;
};




int main()
{
	node *head=NULL,*n1=NULL,*n2=NULL,*n3=NULL,*n4=NULL;
	n1=new node;
	n2=new node;
	n3=new node;
	n4=new node;
	cin>>n1->data;
	n1->next=n2;
	cin>>n2->data;
	n2->next=n3;
	cin>>n3->data;
	n3->next=n4;
	cin>>n4->data;
	n4->next=NULL;
	head=n1;
	cout<<"before Delete "<<endl;

	for(node *loc=head;loc!=NULL;loc=loc->next)
		cout<<loc->data<<endl;

	
	node *cur=n2;
	while(cur)
	{
		node *c1=cur;
		cur=cur->next;
		delete c1;
	}

	

	n2->next=NULL;

	cout<<"after Delete"<<endl;
	for(node *loc=head;loc!=NULL;loc=loc->next)
		cout<<loc->data<<endl;



	system("pause");
	return 0;
}
Your while() loop is also deleting n2.
So an easy "fix" is to start from n2->next instead of n2.

node *cur=n2->next;

That said, your code can be much improved. Some problems:

1) Your program has memory leaks.

In C++, every new must have a corresponding delete.
If it doesn't, a "memory leak" occurs. This means that the program will waste memory by not deallocating it when it's no longer needed. It is important to learn early that memory leaks must be avoided in C++.

2) You leave it to the user to build the actual list, by modifying the nodes.

If you want to do this properly, I suggest you read portions of the C++ Tutorial:

http://www.cplusplus.com/doc/tutorial/classes/
http://www.cplusplus.com/doc/tutorial/templates/#class_templates

Your goal would be to create a simple list class template that offers insert() and remove() operations, but never lets the user manually modify the node's.
well thank you for your advice's , i know a little bit about the memory leak but we had not discuss it in the class room till that time i will read the Tutorials ...Thank you very much
Topic archived. No new replies allowed.