您的位置:首页 > 其它

带头单链表删除特定元素实现

2014-06-27 16:50 141 查看
要求:输入链表元素,再输入需要删除的元素,最后显示删除元素后的链表元素

例如:

输入:3->4->7->3->4

3

输出:4->7->4

实现代码如下:

#include<iostream>
using namespace std;
struct node
{
int data;
node * next;
};

node * creat_link(int const n)
{
node * head, * s, * p;
p = head = (node *)malloc(sizeof(node));
for(int i = 0; i < n; i++)
{
int x;
cin >> x;
s = (node *)malloc(sizeof(node));
s->data = x;
p->next = s;
p = s;

}
p->next = NULL;
return head;
}
int show(node * head)
{
if(head == NULL)
return -1;
node * p = head->next;
while(p->next != NULL)
{
cout << p->data << ends;
p = p->next;
}
cout << p->data << endl;
return 0;
}
node * del(node * head, int x)
{
if((head == NULL) || (head->next == NULL))
return NULL;

node * r = NULL;
node * p = head;
while(p->next != NULL)
{
if(p->next->data == x)
{
r = p->next;
p->next = p->next->next;
free(r);

}
else
p = p->next;
}
return head;
}
int main()
{
int n;
cin >> n;
//cout << "n = " << n << endl;
node * head = creat_link(n);
//show(head);
int m;
cin >> m;
del(head, m);
show(head);
system("pause");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐