#include
#include<stdlib.h>
using namespace std;
struct link
{
int data;
struct link* next;
};
struct link* Add(struct link* head)
{
struct link* p = NULL, * pr = head;
p = (struct link*)malloc(sizeof(struct link));
if (p == NULL)
{
cout << “" << endl;
cout << “申请内存失败!” << endl;
exit(0);
}
if (head == NULL)
{
head = p;
}
else
{
while (pr->next != NULL)
{
pr = pr->next;
}
pr->next = p;
}
cin >> p->data;
cout << "” << endl;
p->next = NULL;
return head;
}
void Display(struct link* head)
{
int i = 1;
struct link* p = head;
while (p != NULL)
{
cout <<"("<<i<<")"<<"->"<< p->data <<" ";
p = p->next;
i++;
}
cout << endl;
}
void FreeMemory(struct link* head)
{
struct link* p = head, * pr = NULL;
while (p != NULL)
{
pr = p;
p = p->next;
free(pr);
}
}
struct link* Del(struct link* head, int nodeData)
{
struct link* p = head, * pr = head;
if (head == NULL)
{
cout << “" << endl;
cout << “链表为空!” << endl;
return 0;
}
while (nodeData!=p->data && p->next != NULL)
{
pr = p;
p = p->next;
}
if (nodeData == p->data)
{
if (p == head)
{
head = p->next;
}
else
{
pr->next = p->next;
}
free§;
}
else
{
cout << "” << endl;
cout << “未找到要删除的元素!” << endl;
}
return head;
}
int main()
{
struct link* head=NULL;
char c;
int key=0,nodeData=0;
while (1)
{
cout << “" << endl;
cout << " 1—添加新结点 2—删除某个结点 " << endl;
cout << " 3— 其他—退出链表操作 " << endl;
cout << "” << endl<<endl;
cout << “请输入想要执行操纵的代表数字:” << endl;
cin >> key;
cout << “" << endl;
switch (key)
{
case 1:
while (1)
{
cout << “请输入数值:” << endl;
head = Add(head);
Display(head);
cout << "” << endl;
cout << “是否继续输入数值? 请输入:N或Y (N代表否,Y代表是)” << endl;
cin >> c;
cout << “*******************************************************” << endl;
if (c == ‘N’ || c == ‘n’)
{
break;
}
else if (c == ‘Y’ || c == ‘y’)
{
}}break;case 2:Display(head);cout << "*******************************************************" << endl;cout << "请输入要删除的数据:" << endl;cin >> nodeData;head = Del(head, nodeData);cout << "*******************************************************" << endl;Display(head);break;default:cout << "*******************************************************" << endl;cout << "已清除链表所占内存空间!" << endl;FreeMemory(head);return 0;break;} }
1234567891011121314151617181920}