从单向链表中删除指定值的节点(不使用容器)
从单向链表中删除指定值的节点
http://www.nowcoder.com/questionTerminal/f96cd47e812842269058d483a11ced4f
#include<bits/stdc++.h>
using namespace std;
class MylistNode{
public:
struct listNode {
int val;
listNode* next;
listNode() { val = 0; next = nullptr;}
listNode(int _val) { val = _val; next = nullptr;}
};
public:
static void insert(int nowVal,int preVal,listNode* head)
{
listNode* cur = new listNode(nowVal);
while(head != nullptr)
{
if(preVal != head->val)
head = head->next;
else
{
listNode* tmp = head->next;
head->next = cur;
cur->next = tmp;
break;
}
}
return ;
}
static void remove(int removeVal,listNode* head)
{
while(head != nullptr && head->next != nullptr)
{
if(removeVal != head->next->val)
head = head->next;
else
{
listNode* tmp = head->next;
head->next = head->next->next;
delete tmp;
break;
}
}
return ;
}
static void printListNode(listNode* head)
{
while(head != nullptr)
{
cout << head->val << " ";
head = head->next;
}
cout << endl;
}
};
int main()
{
int nodeNums = 0;
int headVal = 0;
while(cin >> nodeNums >> headVal)
{
MylistNode::listNode* head = new MylistNode::listNode(headVal);
nodeNums--;
while(nodeNums--)
{
int nowVal;
int preVal;
cin >> nowVal >> preVal;
MylistNode::insert(nowVal,preVal,head);
}
int removeVal;
cin >> removeVal;
MylistNode::remove(removeVal,head);
MylistNode::printListNode(head);
}
return 0;
} 
查看13道真题和解析