您的位置:首页 > 其它

删除链表中和某一个数相同的元素(单向链表)哈理工oj1546

2015-03-21 19:35 441 查看
#include<iostream>
#include<stdlib.h>
#include<string.h>

using namespace std;
struct Node
{
int nValue;
Node *pNext;
};

void CreateList(Node **pHead,Node **pEnd,int n)
{
int nValue;
for(int i=0;i<n;i++)
{
cin>>nValue;
Node *temp=(Node*)malloc(sizeof(Node));
temp->nValue=nValue;
temp->pNext=NULL;
if(NULL==(*pHead))
{
(*pHead)=temp;
(*pEnd)=temp;
}
else
{
(*pEnd)->pNext=temp;
(*pEnd)=temp;
}
}
}
void Pop_Front(Node **pHead,Node **pEnd)
{
if(pHead==NULL)
{
return ;
}
if((*pHead)==(*pEnd))
{
free(*pHead);
*pHead=NULL;
*pEnd=NULL;
return ;
}
Node *pDel=(*pHead);
(*pHead)=(*pHead)->pNext;
free(pDel);
pDel=NULL;
}
void Pop_Back(Node **pHead,Node **pEnd)
{
if(pHead==NULL)
{
return ;
}
if((*pHead)==(*pEnd))
{
free(*pHead);
*pHead=NULL;
*pEnd=NULL;
return ;
}
Node *temp=(*pHead);
while(temp->pNext!=(*pEnd))
{
temp=temp->pNext;
}
Node *pDel=(*pEnd);
(*pEnd)=temp;
(*pEnd)->pNext=NULL;
free(pDel);
pDel=NULL;
}
void Delete(Node **pHead,Node **pEnd,int nValue)
{
if(pHead==NULL)
{
return ;
}
Node *temp=(*pHead);
while(temp)
{
if (temp->nValue == nValue)
{
// 看这个节点 是头还是中间 还是尾
if (temp == (*pHead))
{
Pop_Front(pHead,pEnd);
}
else if(temp == (*pEnd))
{
Pop_Back(pHead,pEnd);
}
else
{
Node *pDel=temp;
Node *pTemp=(*pHead);
while(pTemp->pNext!=temp)
{
pTemp=pTemp->pNext;
}
temp=temp->pNext;
pTemp->pNext=temp;
free(pDel);
pDel = NULL;
}
return ;
}
temp=temp->pNext;
}
}
void ShowList(Node *pHead,Node *pEnd)
{
Node *temp=pHead;
if(pHead==NULL)
{
return ;
}
while(temp->pNext)
{
cout<<temp->nValue<<" ";
temp=temp->pNext;
}
cout<<temp->nValue;
cout<<endl;
}
void delAll(Node **pList)
{
Node *del;
while(*pList != NULL)
{
del = *pList;
*pList = (*pList)->pNext;
free(del);
}
}
int Length(Node *pHead)
{
int i=0;
Node *temp=pHead;
while(temp)
{
i++;
temp=temp->pNext;
}
return i;
}

int main()
{
int n;
int nDeleteValue;
int m;
char str[10];
int nInsertValue,j;
while(cin>>n)
{
Node *pHead=NULL;
Node *pEnd=NULL;
CreateList(&pHead,&pEnd,n);
cin>>m;
cout<<n<<endl;
ShowList(pHead,pEnd);
for(int i=0;i<n;i++)
{
Delete(&pHead,&pEnd,m);
}
cout<<Length(pHead)<<endl;
ShowList(pHead,pEnd);
delAll(&pHead);
}
//system("pause");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐