返回顶部

收藏

C语言处理双向链表的排序问题

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

typedef struct node{ 
    int data; 
    struct node *pre; 
    struct node *next; 
} Node;

int get_int(void);
Node* get_node(void);
void insert(Node*p,Node* new_node);

int 
main()
{
    Node * p;
    Node * head = (Node*)malloc(sizeof(Node));
    head->pre = NULL;
    head->next = get_node();
    head->next->pre = head;
    printf("please enter the number 'q' to quit:");
    while (1)
    {
        p = get_node();
        p->data = get_int();
        if (p->data ==0)
            break;
        insert(head,p);
    }
    while (head->next!=NULL)
    {
        printf("%d ",head->next->data);
        head->next = head->next->next;
    }
    return 0;
}

//得到整数
int
get_int(void)
{
    int input;
    char ch;
    while (scanf("%d",&input)!=1)
    {
        while((ch=getchar())!='\n')
            putchar(input);
        printf(" is not an integer.\nPlease enter an integer value,such as 25,-178,or 3;\n");
    }
    return input;
}

//向链表插入新链
void 
insert(Node*p,Node* new_node)
{
    if (p->next->data == 0)
    {
        p->next->data = new_node->data;
        return;
    }
    Node* scan = p->next;
    while (1)
    {
        if (scan->data < new_node->data)
        {
            if (scan->next != NULL)
                scan = scan->next;
            else
            {
                scan->next = new_node;
                new_node->pre = scan;
                break;
            }
        }
        else
        {
            new_node->pre = scan->pre;
            new_node->next = scan;
            scan->pre->next = new_node;
            scan->pre = new_node;
            break;
        }
    }
}

//获得新节点
Node* 
get_node(void)
{
    Node* new_node = (Node*)malloc(sizeof(Node));
    new_node->next = NULL;
    new_node->pre = NULL;
    new_node->data = 0;
    return new_node;
}

标签:链表,排序,C语言

收藏

0人收藏

支持

0

反对

0

发表评论