删除链表中和某一个数相同的元素(单向链表)哈理工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; }
相关文章推荐
- 数据结构 - 如何删除单向链表的倒数第m个元素?
- 单链表的创建(头插尾插),表长,输出,插入,删除,查找,逆置,分解长两个链表(奇数偶数链表),查找倒数第k个元素,产出相同元素
- 删除环状单向链表中的重复元素的操作
- [笔试题 7][c/c++]删除两个双向链表中相同元素的所有节点
- ArrayList删除集合中某一属性相同的元素方法(推荐)
- 华为OJ——从单向链表中删除指定值的节点
- 删除单向链表头元素
- C语言单向动态链表程序,实现链表的建立,合并,重新排序,链表元素的插入与删除,以及根据元素成员的值进行元素删除。
- 已知线性表中元素以值递增有序排列,并以单链表作为存储结构,设计一个算法,删除表中值相同的多余元素
- OJ-------从单向链表中删除指定节点
- 删除两个双向链表中相同元素的所有节点
- SDUT_OJ_1464-链表-删除指定元素
- ArrayList删除集合中某一属性相同的元素
- 面试题11 删除单向链表中的一个元素 但是只提供这个元素的操作权
- 单向链表O(1)删除中间元素
- 删除相同元素链表实现
- 山东理工OJ【2122】数据结构实验之链表七:单链表中重复元素的删除(两种思想)
- 单链表 (反序,删除相同元素)
- 山东理工OJ 2122 数据结构实验之链表七:单链表中重复元素的删除
- 华为OJ(从单向链表中删除指定值的节点)