linked list
Mar 23, 2016 at 3:17am UTC
I have to write a function that takes linked list of items and deletes all repetitions from the list. but I have some errors. can you help me with the code. this is what I have tried so far!
list.h file
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#ifndef _LIST_H
#define _LIST_H
struct node {
public :
int data;
node * next;
public :
void removedup();
void insert();
void print();
};
#endif
list.cpp file
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
#include<iostream>
#include"list.h"
void insert(struct node** head, int new_data);
void print(struct node *node);
struct node
{
int data;
struct node *next;
};
void removedup(struct node *startnode)
{
struct node *p1, *p2, *dup;
p1 = startnode;
while (p1 != NULL && p1->next != NULL)
{
p2 = p1;
while (p2->next != NULL)
{
if (p1->data == p2->next->data)
{
dup = p2->next;
\
p2->next = p2->next->next;
free(dup);
}
else
{
p2 = p2->next;
}
}
p1 = p1->next;
}
}
main.cpp file
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 70 71 72 73 74
#include <iostream>
#include "list.h"
using namespace std;
int main()
{
struct node *startnode = NULL;
insert(&startnode, 5);
insert(&startnode, 10);
insert(&startnode, 10);
insert(&startnode, 15);
insert(&startnode, 15);
insert(&startnode, 20);
insert(&startnode, 25);
cout << "\n list before removing duplicates " << endl;
print(startnode);
removedup(startnode);
cout << "\n list after removing duplicates " << endl;
print(startnode);
getchar();
}
void insert(struct node** head, int new_data)
{
struct node* new_node =
(struct node*) malloc(sizeof (struct node));
new_node->data = new_data;
new_node->next = (*head);
(*head) = new_node;
}
void print(struct node *node)
{
while (node != NULL)
{
cout << node->data << endl;
node = node->next;
}
}
Last edited on Mar 23, 2016 at 3:27am UTC
Mar 23, 2016 at 5:57am UTC
What error are you getting? compilation or run time error.
Looks like logic is ok .
Last edited on Mar 23, 2016 at 8:17am UTC
Topic archived. No new replies allowed.