linked list
Write program to delete each node, if has a repeated value
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 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
|
#include <iostream>
using namespace std;
struct list
{
int data;
list *next;
};
list *head = NULL;
void add2List(list *node2List)
{
node2List->next = head;
head = node2List;
}
void remove()
{
list *root = head;
list *afterRoot = root->next;
list *bf_root = root;
while(root)
{
while(afterRoot)
{
if(afterRoot->data == root->data)
{
list *delNode = afterRoot;
afterRoot = afterRoot->next;
bf_root->next = afterRoot;
delete delNode;
}
else
{
bf_root = afterRoot;
afterRoot = afterRoot->next;
}
}
root = root->next;
}
}
int main()
{
list *node;
int val;
cout << "Adding values to list :\n";
cout << ">>";
while(cin >> val)
{
cout << ">>";
node = new list;
node->data = val;
node->next = NULL;
add2List(node);
}
remove();
list *temp = head;
while(temp)
{
cout << temp->data << " ";
temp = temp->next;
}
return 0;
}
|
It works good with me
What I want is your suggestions in this code and also if possible to give me advice that can help to be my code more effective in the future .
sorry for my bad english
Instead of using a global variable and functions that modify it, make functions that take the list they are modifying as an argument.
Even better, make the functions part of the structure as member functions.
@firedraco
thank u so much
Topic archived. No new replies allowed.