#include <iostream> using namespace std; //链表的创建、查找、删除、增加元素 struct node { char ch; node *next; }; bool createList(node* &head) { head = new node; head->ch = 'S'; head->next = NULL; char ch; cin.get(ch); while(ch != '#') { node *pNode = new node; if (pNode == NULL) { return false; } else { pNode->ch = ch; pNode->next = head->next; head->next = pNode; } cin.get(ch); } return true; } bool creatNormalOrdereList(node *&head) { head = new node; head->ch = 'S'; head->next = NULL; node* s = head; char ch; cin.get(ch); while(ch != '#') { node* pNode = new node; if (pNode == NULL) { return false; } else { pNode ->ch = ch; pNode->next = NULL; s->next = pNode; s = pNode; } cin.get(ch); } } void printList(node* head) { node* p = head; while(p !=NULL) { cout << p->ch <<" "; p = p->next; } } int searchList(node* head, char ch) { node* p = head; int i = -1; while(p != NULL) { ++i; if(p->ch == ch) { break; } p = p->next; } return i; } void delElement(node* head, char ch) { node *p = head->next, *q = head; while(p != NULL) { if(p->ch == ch) { q->next = p->next; return; } q = p; p = p->next; } cout <<"不存在此元素"<<endl; } void addElement(node* head, char ch) { node* p =new node; p->ch = ch; p->next = head->next; head->next = p; } int main() { node *head; //创建链表 cout << "创建链表:"<<endl; //createList(head); creatNormalOrdereList(head); cout <<endl; //遍历链表 cout <<"输出链表:"<<endl; printList(head); cout <<endl; //查找元素 cout <<"请输入您想要找的字符:"<<endl; char ch; int index; cin >> ch; index = searchList(head, ch); if(index == -1) { cout <<"链表中不含有该字符!"<<endl; } else { cout <<"该字符在第 "<<index <<" 位置!"<<endl; } //删除元素 cout << "请输入你要删除的元素:"<<endl; cin >> ch; delElement(head,ch); cout <<endl<<"输出删除 "<<ch<<" 后的链表:"<<endl; printList(head); cout<<endl; //增加元素 cout <<"请输入你想要添加的元素:"<<endl; cin >> ch; addElement(head, ch); cout <<"输出添加元素 "<<ch <<" 后的链表:"<<endl; printList(head); cout <<endl; return 0; }