小百求助,关于简单链表的建立与使用,求大神帮助,谢谢
AXDii 2017-03-14 10:17:01 小白程序如下, 目的是输出两个链表的交集和并集:
#include<stdio.h>
#include<stdlib.h>
typedef struct Node List;
typedef List * PrtToNode;
typedef int ElementType;
struct Node{
ElementType Element;
PrtToNode next;
};
PrtToNode MakeList();
void ShowList(PrtToNode head);
PrtToNode Intersection(PrtToNode P, PrtToNode L);
PrtToNode Union(PrtToNode P, PrtToNode L);
int main()
{
//创建P、L
PrtToNode P = NULL;
PrtToNode L = NULL;
PrtToNode intersections = NULL;
PrtToNode unions = NULL;
printf("请输入P的元素:\n");
P = MakeList();
printf("请输入L的元素:\n");
L = MakeList();
intersections = Intersection(P, L);
unions = Union(P, L);
printf("\n输出P和L的交集:\n");
ShowList(intersections);
printf("\n输出P和L的并集:\n");
ShowList(unions);
return 0;
}
PrtToNode MakeList()
{
PrtToNode head = NULL;
PrtToNode ps = NULL;
PrtToNode pend = NULL;
ps = (PrtToNode)malloc(sizeof(List));
pend = ps;
for(int i = 0; i < 5; i++){
scanf("%d", &(ps ->Element));
if (head == NULL)
head = ps;
else
pend ->next = ps;
pend = ps;
ps = (PrtToNode)malloc(sizeof(List));
}
pend ->next = NULL;
pend = pend->next;
free(ps);
return head;
}
PrtToNode Intersection(PrtToNode P, PrtToNode L)
{
PrtToNode head = NULL;
PrtToNode ps = NULL;
PrtToNode pend = NULL;
PrtToNode pp = P;
PrtToNode pl = L;
ps = (PrtToNode)malloc(sizeof(List));
pend = ps;
while(pp){
while(pl){
if(pp ->Element != pl ->Element) {
pl = pl ->next;
continue;
}
ps ->Element = pp ->Element;
if(head == NULL)
head = ps;
else
pend ->next = ps;
pend = ps;
ps = (PrtToNode)malloc(sizeof(List));
pl = pl ->next;
}
pl = L;
pp = pp ->next;
}
pend ->next = NULL;
pend = pend ->next;
free(ps);
free(pl);
free(pp);
free(pend);
return head;
}
PrtToNode Union(PrtToNode P, PrtToNode L) //在这里,小白隐藏了Union函数
{
/* PrtToNode ps = NULL;
PrtToNode head = NULL;
PrtToNode pp = P;
PrtToNode pl = L;
PrtToNode pend = NULL;
while(pp){
ps = (PrtToNode)malloc(sizeof(List));
ps ->Element = pp ->Element;
if(head == NULL)
head = ps;
else
pend ->next = ps;
pend = ps;
pp = pp ->next;
}
pp = P;
while(pp){
while(pl){
if(pp ->Element != pl ->Element && pl ->Element == -1101) {
pl = pl ->next;
continue;
}
pl ->Element = -1101;
pl = pl ->next;
}
pl = L;
pp = pp ->next;
}
puts("233 ");
while(pl){
if(pl ->Element == -1101) {
pl = pl ->next;
continue;
}
ps = (PrtToNode)malloc(sizeof(List));
ps ->Element = pl ->Element;
pend ->next = ps;
pend = ps;
}
pend ->next = NULL;
free(ps);
return head;
*/
}
void ShowList(PrtToNode head)
{
PrtToNode ps = head;
while(ps){
printf("%d ", ps ->Element);
ps = ps->next;
}
}
小白隐藏了union函数的內容, 但unions这个元素还是接受了一个指针,并且输出与P这个元素的内容一样,小白调式多次不会解决,请问为什么会出现这个现象?如何解决这个问题?谢谢。