【數據結構】單鏈表—刪除表中數值介於給定值之間的元素

設在一個帶頭結點的單鏈表中所有元素結點的數據值無序,試編寫一個函數,刪除表中所有介於給定的兩個值(作爲函數參數給出)之間的元素的元素

//帶頭結點的單鏈表無序
//刪除數比表中所有值介於在兩個給定值(作爲函數參數給出)之間的元素。
#include<stdio.h>
#include<stdlib.h>
struct Lnode
{
    int data;
    Lnode *next; 
};
int Init(struct Lnode *L, int i)
{
    struct Lnode *p;
    struct Lnode *q=L;
    int j=0;
    while(j<i)
    {
        p = (struct Lnode *)malloc(sizeof(struct Lnode));
        scanf("%d",&(p->data));
        p->next =NULL;
        q->next = p;
        q= p;
        j++;
    }
    return 0;
}
int rangedelete(struct Lnode *L,int x,int y)
{
    if(x>y)
    {
        int z = x;
        x=y;
        y=z;
    }
    struct Lnode *p,*q;
    p = L->next;
    q= L;
    while(p!=NULL)
    {
        if(x<=p->data&&p->data<=y)
        {
            q->next = p->next;
            free(p);
            p = q->next;
        }
        else 
        {
            q= p;
            p = p->next;
        }
    }
    return 0;
}
int main()
{
    struct Lnode Head;
    struct Lnode *L=&Head;
    L->next = NULL;
    int i = 5;
    Init(L,i);
    printf("請輸入兩個值!");
    int x,y;
    scanf("%d",&x);
    scanf("%d",&y);
    rangedelete(L,x,y);
    printf("\n結果如下!\n");
    struct Lnode *p =L->next;
    while(p!=NULL)
    {
        printf("%d",(*p).data);
        p=(*p).next;
    }
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章