#include<stdio.h> #include<malloc.h> #include<stdlib.h> //链表结构体 typedef struct Node{ int data; struct Node * pNext; }NODE ,*PNODE; //c创建与销毁 PNODE create_list(void); void destroy(PNODE H); //主函数 int main() { PNODE P; P=create_list(); destroy(P); return 0; } PNODE create_list(void)//创建链表 { int len;int i; int val; PNODE pHead=(PNODE)malloc(sizeof(NODE));//分配头节点 if(NULL==pHead) {printf("分配失败,程序终止\n");return(NULL); } PNODE pTail=(PNODE)malloc(sizeof(NODE));//分配头节点 if(NULL==pTail) { printf("分配失败,程序终止\n"); return (NULL); } PNODE Tail=pHead; pTail->pNext=NULL; printf("请您输入生成的链表节点个数:"); scanf("%d",&len); for(i=0;i<len;i++)//按序输入节点及内容 { printf("请输入第%d个节点的值:",i+1); scanf("%d",&val); PNODE pNEW=(PNODE)malloc(sizeof(NODE)); if(pNEW==NULL) { printf("分配失败,程序终止"); return(NULL);} pNEW->data =val; pTail->pNext=pNEW; pNEW->pNext=NULL; pTail=pNEW; } return pHead; } //销毁 void destroy(PNODE H) { PNODE p,q; p=H; while(p){ q=p; p=p->pNext; free(q); printf("已销毁"); } }
[此贴子已经被作者于2016-3-23 10:19编辑过]
#include<stdio.h> #include<malloc.h> #include<stdlib.h> //链表结构体 typedef struct Node { int data; struct Node * pNext; }NODE, *PNODE; PNODE create_list(void); //创建 void destroy(PNODE H);//销毁 void Out_Pnode(PNODE p);//输出 PNODE AB (PNODE A,PNODE B);//求A交B PNODE Locate(PNODE B,int x);//遍历 //主函数 int main() { PNODE A ;//创建A集合 PNODE B ; PNODE C ;//C=A&&B printf("输入A集合的数值\n"); A = create_list(); if (A == NULL)//判断下返回值 { return 0;} printf("输出A集合的数值\n"); Out_Pnode(A);//输出A集合 printf("\n"); printf("\n"); printf("输入B集合的数值\n"); B = create_list(); if (B == NULL) { return 0;} printf("输出B集合的数值\n"); Out_Pnode(B); printf("\n"); printf("\n"); C = AB ( A, B); printf("输出C集合的数值\n"); Out_Pnode(C); printf("\n"); printf("\n"); printf("销毁A\n"); destroy(A); printf("销毁B\n"); destroy(B); printf("销毁C\n"); destroy(C);//??????会出问题 return 0; } PNODE create_list(void)//创建链表 { int len; int i; int val; PNODE pTail ; pTail = (PNODE)malloc(sizeof(NODE)); PNODE k=pTail; pTail->pNext=NULL; printf("请您输入生成的链表节点个数:"); scanf("%d", &len); for (i = 0; i<len; i++)//按序输入节点及内容 { printf("请输入第%d个节点的值:", i + 1); scanf("%d", &val); PNODE pNEW = (PNODE)malloc(sizeof(NODE)); if (pNEW == NULL) { printf("分配失败,程序终止"); return(NULL); } pNEW->data = val; pNEW->pNext = NULL; k->pNext = pNEW; k = pNEW; } return pTail; } //销毁 void destroy(PNODE H) { PNODE p, q; p=H; while(p) { q=p; p=p->pNext; free(q); } H=NULL; printf("已销毁\n"); } //求A交B PNODE AB (PNODE A,PNODE B){ int x; PNODE pre,p; pre=A;p=pre->pNext; while(p){ x=p->data; if(!Locate(B,x)) { pre->pNext=p->pNext; free(p); p=pre->pNext; } else { pre=p; p=p->pNext; } } return A; } PNODE Locate(PNODE B,int x) { PNODE p=B->pNext; while (p&&p->data!=x) p=p->pNext; return (p); } void Out_Pnode(PNODE p)//输出链表 { PNODE q; q=p->pNext; if(!p) printf("表不存在\n"); while(q) { printf("%d ",q->data ); q=q->pNext; } }