划分链表

#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
    int key;
    struct node *next;
}NODE;

void DisplayNode(NODE *p)
{
    while(p->next!=NULL)
    {
        printf("%d->",p->key);
        p = p->next;
    }
    printf("%d",p->key);
}
int Lookup(NODE * list_a,int x)
{
    while(list_a!=NULL)
    {
        if(list_a->key==x)
            return 1;
        list_a=list_a->next;
    }
    return 0;
}
NODE *AppendNode()
{
    NODE *head = NULL;
    NODE *tail = NULL;
    int k;
    while(scanf("%d",&k)!=0)//确保输入的数据为整型,输入非数字时结束该过程
    {
        NODE *p = (NODE*)malloc(sizeof(NODE));
        p->key = k;
        p->next = NULL;
        if(head==NULL)
        {
            head = p;
            tail = p;
        }
        else
        {
            tail->next = p;
            tail = p;
        }
    }
    getchar();
    return head;
}
NODE *Partition(NODE *list_a,int x)
{
    NODE *p1 = NULL,*p2= NULL,*p = list_a;
    //struct node *Ldata = NULL,*Rdata = NULL;
    NODE *pr1=(NODE*)malloc(sizeof(NODE));
    NODE *pr2=(NODE*)malloc(sizeof(NODE));
    while (p != NULL)
    {
        if (p->key < x)
        {
            if (p1 == NULL)
            {
                p1 = p;
                pr1 = p;
            }
            else
            {
                p1->next = p;
                p1 = p1->next;
            }
        }
        else
        {
            if (p2 == NULL)
            {
                p2= p;
                pr2 = p;
            }
            else
            {
                p2->next = p;
                p2= p2->next;
            }
        }
        p = p->next;
    }
    p1->next = pr2;
    p2->next = NULL;
    return pr1;
}

int main()
{
    int x,choose;
    NODE *head = NULL;
    NODE *head2 = NULL;
    printf("Please input a series of number:(End up with a letter)\n");
    head = AppendNode();
    printf("You list is:");
    DisplayNode(head);
    printf("\nplease choose a number you had enter:\n");
    scanf("%d",&x);
    choose=Lookup(head,x);
    while(choose!=1)
    {
        printf("Enter wrong!Please try again!");

        scanf("%d",&x);
        choose=Lookup(head,x);
    }
    head2 =Partition(head,x);
    printf("\nAfter sort:\n");
    DisplayNode(head2);
}

 

posted @ 2020-10-10 17:43  倔强jujiang  阅读(79)  评论(0编辑  收藏  举报