Skip to content

Instantly share code, notes, and snippets.

@nkoehring
Created December 27, 2013 04:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nkoehring/8142569 to your computer and use it in GitHub Desktop.
Save nkoehring/8142569 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
struct Point {
int x;
int y;
struct Point *next;
};
static struct Point *head = NULL;
static struct Point *tail = NULL;
struct Point* createList(int x, int y) {
struct Point *ptr = (struct Point*)malloc(sizeof(struct Point));
if( NULL == ptr ) return NULL;
ptr->x = x;
ptr->y = y;
ptr->next = NULL;
head = tail = ptr;
return ptr;
}
struct Point* extendList(int x, int y) {
if( NULL == tail ) return createList(x, y);
int i = 0;
struct Point *tmp = head;
struct Point *next = head->next;
struct Point *ptr = (struct Point*)malloc(sizeof(struct Point));
if( NULL == ptr ) return NULL;
ptr->x = x;
ptr->y = y;
while ( NULL != tmp && x > tmp->x ) {
i++;
//printf("%02d,%02d\n", x, y, next->x, next->y);
if( NULL == next ) {
ptr->next = NULL;
tmp->next = ptr;
break;
} else {
if( x < next->x || (x == next->x && y < next->y) ) {
ptr->next = next;
tmp->next = ptr;
break;
}
}
tmp = tmp->next;
next = tmp->next;
}
if( head == tmp ) {
ptr->next = head;
head = ptr;
}
printf("Durchläufe: %d\n", i);
return ptr;
}
void printList() {
struct Point *tmp = head;
int i = 0;
while ( NULL != tmp ) {
printf("%04d: % 2d,% 2d\n", ++i, tmp->x, tmp->y);
tmp = tmp->next;
if(i>50) {
printf("Whoops…\n");
break;
}
}
}
void readNumbers() {
int x, y, ch;
bool lbState = false; /* double linebreak? */
while(1) {
ch = getc(stdin);
if(ch == EOF || ch == '\n') {
if(lbState) break;
extendList(x, y);
lbState = true;
continue;
}
lbState = false;
ungetc(ch, stdin);
if(scanf("%d %d", &x, &y) == EOF) break;
}
printList();
}
int main() {
readNumbers();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment