deleting a node in singly linked list if it is less than any of the successor nodes


Problem
#include <stdio.h>
#include <stdlib.h>


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

typedef Node *list;

typedef struct {
list l;
int m;
}Ret;

Ret del(list l, Node *prev) {

Ret r = {NULL, 0};

if(l == NULL)
return r;

r = del(l->next, l);


if(r.m > l->data) {

if(prev)
prev->next = r.l;

free(l);

} else {

r.m = l->data;
r.l = l;
}


return r;

}

list append(list l, int n) {

Node * node = calloc(sizeof(Node), 1);
node->data = n;

if(l == NULL)
return node;

list ret = l;

while(l->next)
l = l->next;

l->next = node;

return ret;
}


void print(list l){

while(l) {
printf("%d ", l->data);
l = l->next;
}

printf("\n");
}

int main() {

int a[] = {7, 4, 8, 5, 2, 7, 3, 6};

int i;

list l = NULL;

for(i = 0; i < sizeof(a)/sizeof(int); ++i)
l = append(l, a[i]);


Ret r = del(l, NULL);

print(r.l);
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s