lundi 2 mars 2015

Create an ordered single linked list with numbers



So up until now this is the code I have. I'm having problems implementing the main function because linked-lists are a new subject for me. Could someone explain me what should I include to have an output like this


The output should look like that after inserting 2, 0, 3, 5 and 4 in an, initially, empty list:


2


0 2


0 2 3


0 2 3 5


0 2 3 4 5



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


typedef struct node {

int number;
struct node *next;

} NODE;

NODE* insert(NODE *, int);
NODE* delete(NODE *, int);
void traverse(NODE *);
NODE * search(NODE *head, int data);

main(){

list *newnode, *start = NULL; // this will point to the first node of the list


}


NODE *search(NODE *head, int data){ //search for the right position to add data

NODE *previous=NULL;
NODE *current=head;

while (current !=NULL && data > current->number)
{
previous=current;
current= current->next;
}
return previous;
}

NODE *insert(NODE *head, int data){ //allocates a new node with data value

NODE * temp;

if (temp = (NODE *)malloc(sizeof(NODE)==(NODE*)NULL))
return 1; //malloc have failed
temp->number = data;

NODE *previous;

previous=search(head,data);

//two cases 1) add at front 2)add elsewhere
if (previous==NULL)
{
temp->next=head;
head=temp;
}
else
{
temp->next = previous->next;
previous->next = temp;
}
return head;

}

void traverse (NODE *head){

NODE * current = head;

while (current != NULL)
{
printf(" %d ", current->number);
current = current->next;
}
printf("\n");
}

NODE* delete(NODE *head, int data)
{
NODE *previous, *temp;
previous=search(head,data);

if(previous==NULL && head->number==data)

{
temp=head;
head=head->next;
free(temp);
}
else if (previous->next !=NULL && previous->next->number==data)
{
temp=previous->next;
previous->next = previous->next->next;
free(temp);
}

return head;
}



Aucun commentaire:

Enregistrer un commentaire