Monday, December 30, 2013

Delete same data in single linked list


#include <stdio.h>
#include <malloc.h>

typedef struct slink {
int data;
struct slink *next;
}node;


int a[] = {1, 2, 3, 3, 1, 2, 2, 1, 8, 9};


void append(node **q, int num)
{
node *temp = *q, *r = NULL;

r = (node *)malloc(sizeof(node));
r->data = num;
r->next = NULL;

if(*q == NULL)
*q = r;
else {
while(NULL != temp->next)
temp = temp->next;
temp->next = r;
}
}

void display(node *temp)
{
printf("\nThe list: ");
while(temp) {
printf("%d ", temp->data);
temp = temp->next;
}
}


void red_del(node **q)
{
node *temp = *q, *new = NULL,  *old = NULL;
int data;

while (temp != NULL && temp->next != NULL) {
new = temp;
data = new->data;
while(new->next != NULL) {
if(data == new->next->data) {
old = new->next;
new->next = new->next->next;
free(old);
} else 
new = new->next;
}
temp = temp->next;
}
}

void revlist(node **q)
{
node *temp1 = *q, *temp2 = NULL, *temp3 = NULL;

if (!temp1) return;

while(temp1) {
temp2 = temp1->next;
temp1->next = temp3;
temp3 = temp1;
temp1 = temp2;
}
if(temp3) *q = temp3;
}

int main()
{
node *head = NULL;


for (i = 0; i < 10; i++)
append(&head, a[i]);
display(head);

revlist(&head);
display(head);

red_del(&head);
display(head);

return 0;
}


Test
The list: 1 2 3 3 1 2 2 1 8 9
The list: 9 8 1 2 2 1 3 3 2 1
The list: 9 8 1 2 3 

No comments: