链表(排序插入)

时间:2014-04-25 06:22:02

标签: c list printing linked-list

此程序创建一个排序列表,然后插入一个元素,使列表仍然保持排序。我认为逻辑是正确的..但是程序不会打印新形成的列表。这是代码。怎么了?

#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
struct list {
        int number;
        struct list *next;
        };
typedef struct list node;
void create(node *);
void print(node *);
void sortedInsert(node **);
main() {
int user_response;
node *head;
head = (node *)malloc(sizeof(node));
create(head);
printf("Look at your creation!! A linked list!!1 heheheh...........\n");
print(head);
printf("Do you want to experience some \"sort\" of thrill?\n1 for yes..\n");
scanf("%d",&user_response);
if(user_response == 1) {
        sortedInsert(&head);
        printf("Look at the marvel of linked list...\n");
        print(head);
}
else {
        printf("Ha\n tired fellow,lack of ambition!!!\n");
        exit(0);
}
return 0;
}
void create(node *head) {
        printf("Enter a number,-999 to stop\n");
        scanf("%d",&head->number);
        if(head->number == -999) {
                head->next = NULL;
        }
        else {
                head->next = (node *)malloc(sizeof(node));
                create(head->next);
    }
}
void print(node *head) {
        if(head->next != NULL) {
                printf("%d-->",head->number);
                print(head->next);
        }
        else {
                printf("%d",head->number);
        }
}

void sortedInsert(node **headRef) {
        node *new_node;
        node *prev_ptr = *headRef;
        node *dummy_ptr = *headRef;
        int key;
        printf("Which value do you wanna insert\n");
        scanf("%d",&key);
        new_node = (node *)malloc(sizeof(node));
        new_node->number = key;
        while((*headRef)->next != NULL) {
                if((*headRef)->number >= key) {
                        prev_ptr->next = new_node;
                        new_node->next = *headRef;
                        *headRef = dummy_ptr;
                }
                else {
                        prev_ptr = *headRef;
                        *headRef = (*headRef)->next;
                }
}

0 个答案:

没有答案