I can't figure out why, but the code is function for all other cases.
This program sorts a linked list from positive values from stdin. In the event of 0, it prints the list with duplicates and remove duplicates. The case I can't resolve is 3 3 2 1 0.
I have no idea why even after tracing it back to the list traversal.
Could someone tell me what I did wrong?
Code:
#include <stdio.h>
#include <stdlib.h>
struct node{
int num;
struct node *next;
};
int main(){
struct node *head;
head = (struct node*)malloc( sizeof(struct node));
head->next = NULL;
struct node *cur;
cur = (struct node*)malloc(sizeof(struct node));
int k;
int count = 0;
while(scanf("%d", &k) == 1){
cur = head;
if(k > 0){
while(cur->next != NULL && cur->next->num <= k)
cur = cur->next;
// Insert after node
struct node *newNode;
newNode = (struct node*)malloc(sizeof(struct node));
newNode->num = k;
newNode->next = cur->next;
cur->next = newNode;
}
else if(k == 0){
cur = head->next;
while(cur != NULL){
printf("%d\n", cur->num);
if(cur->next != NULL){
cur = cur->next;
}
else{
cur = NULL;
}
}
cur = head->next;
while(cur->next != NULL){
if(cur->next->num == cur->num)
while(cur->next->num == cur->num){
if(cur->next->next != NULL)
cur->next = cur->next->next;
else cur->next = NULL;
}
cur = cur->next;
}
}
else
return 1;
}
if(head->next == NULL){
// empty lists are sorted
printf("0\n");
return 0;
}
cur = head->next;
while(cur != NULL){
count++;
cur = cur->next;
}
printf("%d\n", count);
return 0;
}