// 在O(1)时间内删除单链表结点
/*
思考:
很显然链表是一个节点地址不连续的存储结构
删除节点一般很容易会想到是修改p节点的前一个节点的next为p->next
然而除非是双向链表,否则无法在常量级的时间里找到p的前节点
转变思路:
既然改变不了p前节点的next
只能在p 本身动手脚
那可以考虑修改p->data
使得p->data的值为p->next->data的值,同样可以达到效果
*/
#include <iostream>
#include <string>
using namespace std;
int L_length = 0;
template<class T>
struct Node {
T value;
Node *next;
Node() {
next = NULL;
}
Node(const T &data) {
value = data;
next = NULL;
}
const Node& operator=(const Node& n) {
value = n.value;
next = n.next;
return *this;
}
};
template<class T>
void PushinList(Node<T>* &L,const T &t) {
Node<T> *n = new Node<T>(t);
n->next = L->next;
L->next = n;
L_length++;
}
template<class T>
Node<T>* FindP(const Node<T>* L,const int &k) {
Node<T>* p = L->next;
for (int i = 0; i < L_length && i + 1 != k; i++) p = p->next;
return p;
}
template<class T>
void PrintList(const Node<T>* L) {
cout << "打印链表:";
for (Node<T>* p = L->next; p != NULL; p = p->next) cout << p->value << " ";
cout << endl;
}
int main(void) {
Node<string>* L = new Node<string>();
string str;
cout << "创建链表(以-1结尾):";
while (cin >> str && str != "-1")
PushinList(L, str);
PrintList(L);
int k;
cout << "指定节点位置:";
cin >> k;
Node<string>* p = FindP(L, k);
//通过重载=操作符直接拷贝*(p->next)下的所有值给*p
*p = *(p->next);
PrintList(L);
system("pause");
return 0;
}
/*
样例输入:
a b c d e f g h -1
3
样例输出:
h g e d c b a
*/