#include<stdio.h>
#include<stdlib.h>
struct node{
int data;
struct node * nextPtr;
};
typedef struct node LISTNODE;
typedef LISTNODE * LISTNODEPTR;
LISTNODEPTR creatFILOlist();
LISTNODEPTR check(LISTNODEPTR headPtr1,LISTNODEPTR headPtr2);
void destoryList(LISTNODEPTR *hPtr);
LISTNODEPTR creatFILOlist()
{
int num;
LISTNODEPTR headPtr=NULL,lastPtr=NULL,currentPtr=NULL;
scanf("%d",&num);
while(num!=-1){
currentPtr=(LISTNODEPTR)malloc(sizeof(LISTNODE));
if(currentPtr!=NULL){
currentPtr->data=num;
if(headPtr==NULL){
headPtr=currentPtr;
lastPtr=currentPtr;
}
else{
lastPtr->nextPtr=currentPtr; //将新节点连到链表的尾节点上
lastPtr=currentPtr; //修正lasrPtr
}
}
scanf("%d",&num);
}
lastPtr->nextPtr=NULL;
free(lastPtr);
free(currentPtr);
return headPtr;
}
LISTNODEPTR check(LISTNODEPTR headPtr1,LISTNODEPTR headPtr2)
{
LISTNODEPTR p=NULL,q=NULL;
p=(LISTNODEPTR)malloc(sizeof(LISTNODE));
q=(LISTNODEPTR)malloc(sizeof(LISTNODE));
p->nextPtr=headPtr1;
q->nextPtr=headPtr2;
p->data=0;
q->data=0;
while(p->nextPtr!=NULL&&q->nextPtr!=NULL){
if(p->nextPtr->data==q->nextPtr->data){
p=p->nextPtr;
q=q->nextPtr;
}
else if(p->nextPtr->data!=q->nextPtr->data){
if(p->nextPtr!=headPtr1&&q->nextPtr!=headPtr2){
if(p->nextPtr->data==headPtr2->data){
q->nextPtr=headPtr2;
}
else{
p=p->nextPtr;
q->nextPtr=headPtr2;
}
}
else if(q->nextPtr==headPtr2){
p=p->nextPtr;
}
}
}
if(q->nextPtr==NULL)
printf("ListB is the sub sequence of ListA.");
else if(q->nextPtr!=NULL&&p->nextPtr==NULL)
printf("ListB is not the sub sequence of ListA.");
free(p);
free(q);
}
void destoryList(LISTNODEPTR *hPtr)
{
LISTNODEPTR tempPtr=NULL,headPtr=*hPtr;
while(headPtr!=NULL){
tempPtr=headPtr;
headPtr=headPtr->nextPtr;
free(tempPtr);
}
*hPtr=NULL;
}
int main()
{
LISTNODEPTR headPtr1,headPtr2;
headPtr1=creatFILOlist();
headPtr2=creatFILOlist();
check(headPtr1,headPtr2);
destoryList(&headPtr1);
destoryList(&headPtr2);
return 0;
}
Sample 2:
1 2 3 4 5 6 7 8 9 -1
1 2 3 4 5 6 7 8 0 -1
提交后提示我内存超限,我该如何释放内存?
free(lastPtr);
free(currentPtr);
这里不能释放的啊,释放了链表里就是一些野指针了啊
==============
free(p);
free(q);
真是让人心惊胆寒的代码。真敢释放啊。你自己都不知道这时候p和q指向什麽了吧?