数据结构单链表删除操作
#include <iostream>using namespace std;struct Node{ int num; Node* pNext;};Node* pHead = NULL;Node* pEnd = NULL;void CreatList(int n)//创建链表{ Node* temp = new Node; temp->num = n; temp->pNext = NULL; if(!pHead) { pHead = temp; } else { pEnd->pNext = temp; } pEnd = temp;}void DelList(int n){ Node* temp = pHead; while(temp)//当节点不为空 { if(temp!=pEnd)//如果不是尾结点,temp = temp->pNext { if(temp->num == n)//找到则删除 { if(temp == pHead)//如果删除的是头结点 { pHead = temp->pNext; delete temp; } else //如果删除的是中间节点 { Node* TempLast; Node* LinShi; TempLast->pNext = temp; LinShi = temp->pNext; TempLast->pNext = LinShi; delete temp; } } else//如果删除的是尾节点 { Node* LinShi; LinShi->pNext = temp; pEnd = LinShi; delete temp; } } temp = temp->pNext; }}void ShowList(){ Node* temp = pHead; while(temp) { cout<<temp->num<<" "; temp = temp->pNext; } cout<<endl;}int main(){ CreatList(1); CreatList(2); CreatList(3); CreatList(4); CreatList(5); CreatList(6); ShowList(); DelList(1); ShowList(); system("pause"); return 0;}
temp = temp->pNext;//你这儿错了,上边都把temp删掉了,这儿肯定出错啊
[解决办法]
晕 上面代码格式没有弄好 再发一个
struct Node{ int num; Node* pNext;};Node* pHead = NULL;Node* pEnd = NULL;void CreatList(int n)//创建链表{ Node* temp = new Node; temp->num = n; temp->pNext = NULL; if(!pHead) { pHead = temp; } else { pEnd->pNext = temp; } pEnd = temp;}void DelList(int n){ Node* temp = pHead; // 指定需要删除的节点 Node* tempBefor=NULL; // 指定需要删除的节点的前一个 while(temp)//当节点不为空 { if(temp!=pEnd)//如果不是尾结点,temp = temp->pNext { if(temp->num == n)//找到则删除 { if(temp == pHead)//如果删除的是头结点 { pHead = temp->pNext; delete temp; break; } else //如果删除的是中间节点 { tempBefor->pNext=temp->pNext; delete temp; break; } } else//如果删除的是尾节点 { Node* LinShi; LinShi->pNext = temp; pEnd = LinShi; delete temp; break; } } //没找到则继续 tempBefor=temp; temp = temp->pNext; }}void ShowList(){ Node* temp = pHead; while(temp) { cout<<temp->num<<" "; temp = temp->pNext; } cout<<endl;}
[解决办法]
删除单链表的其中某一个时,如果不是头结点,那么就要先搞个节点指向他的前一个,
1 -> 2 -> 3
pre temp
如上如果查到的是要删除temp,那么只需要pre->next = temp->next;然后delete temp;就好了