/*
* 链表相对于数组:
* 插入和删除的效率高;
* 查找效率低;
* 存储额外的节点指针,带来空间上的消耗;
*/
#include <iostream>
using namespace std;
//定义链表的数据结构
struct ListNode{
int val;
struct ListNode *next;
ListNode(int x): val(x), next(NULL){}
};
//创建单向链表
ListNode* list_Create(){
ListNode* pHead, *pCurrent, *pNew;
int data;
pHead = new ListNode(0);
pCurrent = pHead;
cin>>data;
while(data != -1){
pNew = new ListNode(data);
pCurrent->next = pNew;
pCurrent = pNew;
cin>>data;
}
return pHead->next;
}
// 打印单向链表
void list_Print(ListNode* pHead){
if(pHead == NULL) return ;
ListNode* tmp = pHead;
while(tmp){
cout<<tmp->val<<" ";
tmp = tmp->next;
}
cout<<endl;
}
//插入,值x后插入y
ListNode *list_Insert(ListNode* pHead, int x, int y){
if(pHead == NULL) return NULL;
ListNode *pCurrent, *pNew;
pCurrent = pHead;
pNew = new ListNode(y);
while(pCurrent){
if(pCurrent->val == x) break;
pCurrent = pCurrent->next;
}
if(pCurrent == NULL){
cout<<"未找到值为:"<<x<<endl;
}
else{
pNew->next = pCurrent->next;
pCurrent->next = pNew;
}
return pHead;
}
//删除
ListNode* list_Delete(ListNode* pHead, int data){
if(pHead == NULL) return NULL;
ListNode* pPre, *pCurrent;
pPre = pHead;
pCurrent = pPre->next;
// 删除头节点
if(pHead->val == data){
delete pHead;
return pCurrent;
}
while(pCurrent){
if(pCurrent->val == data) break;
pPre = pCurrent;
pCurrent = pCurrent->next;
}
if(pCurrent == NULL){
cout<<"未找到值为:"<<data<<"节点"<<endl;
}
else{
pPre->next = pCurrent->next;
delete pCurrent;
}
return pHead;
}
//销毁单向链表
int list_Destory(ListNode* pHead){
if(pHead == NULL) return 0;
ListNode *t = NULL;
while(pHead){
t = pHead->next;
delete pHead;
pHead = t;
}
return 0;
}
int main(){
ListNode* node = list_Create();
list_Print(node);
int x, y;
//cin>>x>>y;
//list_Print(list_Insert(node, x, y));
cin>>x;
list_Print(list_Delete(node, x));
return 0;
}