數據結構習題——5單鏈表的刪除

time_limit

3000MS

memory_limit

10000KB

description

已知A,B和C爲三個非遞減有序的線性表,均以單鏈表作爲存儲結構。現要求對A表作如下操作:刪去那些既在B表中出現又在C表中出現的元素。試對單鏈表編寫實現上述操作的算法,並釋放A表中的無用結點空間。

input

第一行輸入3個正整數m,n,p(m,n,p<=100),用空格分開,表示三個線性表中的元素個數,其後3行依次輸入A,B,C表中的元素。

output

輸出實現上述操作後的A表。

sample_input

8 5 6

1 2 3 4 5 6 6 7

2 3 5 9 12
2 4 5 6 12 13

sample_output

1 3 4 6 6 7

#include <stdio.h>
#include <stdlib.h>
typedef int ElemType;

typedef struct Node{
    ElemType data;
    struct Node *next;
}LNode,*PLNode;

typedef struct Linklist{
    PLNode head;
}Linklist,*PLinklist;

PLinklist Initlist(int n)
{
    int i;
    PLNode p,q;
    PLinklist plist;

    plist=(PLinklist)malloc(sizeof(Linklist));
	q=plist->head=(PLNode)malloc(sizeof(LNode));
    for(i=0;i<n;i++){
        p=(PLNode)malloc(sizeof(LNode));
        scanf("%d",&p->data);
        q->next=p;
        q=q->next;
    }
    q->next=NULL;
    return plist;
}

ElemType get_list(PLNode p)
{
    return p->data;
}

PLNode locate_list(PLinklist plist,ElemType x)
{
    PLNode p;
    p=plist->head->next;
    while(p!=NULL&&p->data!=x){
        p=p->next;
    }
    return p;
}

void delete_list(PLinklist plist,PLNode p)
{
    PLNode q;
    q=plist->head;
    while(q->next!=p){
        q=q->next;
    }
    q->next=p->next;
    //free(p);
}

void show_list(PLinklist plist)
{
    int i=0;
    PLNode p;
    p=plist->head->next;
    while(p){
        if(0!=i)printf(" ");
        printf("%d",p->data);
        p=p->next;
        i++;
    }
    printf("\n");
}
int main()
{
    PLNode pa,pb,pc,location;
    PLinklist la,lb,lc;
    ElemType x;
    int a,b,c;
    scanf("%d%d%d",&a,&b,&c);

    la=Initlist(a);
    lb=Initlist(b);
    lc=Initlist(c);

    //下面時b和c的交集
    pb=lb->head->next;
    while(pb){
        PLNode t=pb->next;
		x=get_list(pb);
        location=locate_list(lc,x);
        if(NULL==location){
            delete_list(lb,pb);
            pb=t;
        }
        else
            pb=pb->next;
    }

    //下面是差集:
    pa=la->head->next;
    while(pa){
    	PLNode t=pa->next;
        x=get_list(pa);
        location=locate_list(lb,x);
        if(NULL!=location){
            delete_list(la,pa);
            pa=t;
        }
        else
            pa=pa->next;
    }

	show_list(la);
    //printf("Hello world!\n");
    return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章