Skip to content

Instantly share code, notes, and snippets.

@knotman90
Created December 6, 2016 17:14
Show Gist options
  • Save knotman90/3a5f20a44d237f619ac01b089287c789 to your computer and use it in GitHub Desktop.
Save knotman90/3a5f20a44d237f619ac01b089287c789 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include<stdlib.h>
typedef struct node{
int payload;
node* next;
} node;
void print(node* head){
while(head){
printf("%d ",head->payload);
head = head->next;
}
printf("\n");
}
int cmp( const int a, const int b ){
return a>b;
}
node* _insert(node* prec, node*head , const int n ){
if(!head )//insert at end
{
node* aus = (node*)malloc(sizeof(node));
aus->payload = n;
aus->next = 0;
prec->next = aus;
return aus;
}else if (cmp(n,head->payload)){
node* aus = (node*)malloc(sizeof(node));
aus->payload = n;
aus->next = head;
if(prec) prec->next = aus; //new head
return aus;
}
return _insert(head, head->next,n);
}
/*
* If the list is empty simply allocate a node and update the head of the list.
* If the list is not empty then call __insert();
* If the pointer to the newly inserted element is the new head then update the head.*/
node* insert(node* head, const int n){
if(!head)
{
node* aus = (node*)malloc(sizeof(node));
aus->payload=n;
aus->next=0;
return aus;
}
node* ni =_insert(0,head,n);
if(cmp(ni->payload , head->payload))
head=ni;
return head;
}
int main(){
node* head = 0;
for(int i=10;i>0;i--){
int a; scanf("%d",&a);
head=insert(head,a);
print(head);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment