标签:des blog io os sp for 数据 div log
10 56 25 12 33 66 54 7 12 33 12 12
10 56 25 12 33 66 54 7 12 33 12 7 56 25 33 66 54 7 33
代码(比较挫~~~):
#include <iostream>
#include <string>
#include <cstdio>
#include <string.h>
#include <algorithm>
#include <ctype.h>
using namespace std;
struct node
{
int data;
struct node *next;
};
struct node *creat(int n)
{
int i;
struct node *head, *tail, *p;
head=new node;
head->next=NULL;
tail=head;
for(i=0; i<n; i++)
{
p=new node;
cin>>p->data;
p->next=NULL;
tail->next=p;
tail=p;
}
return head;
}
int main()
{
int n, k;
int len;
int i, j;
cin>>n;
struct node *head, *w, *q;
head = creat(n);
cin>>k; //输入要被删除的数据
//输出链表1
w=head->next;
len=n;
cout<<len<<endl;
for(j=0; j<len; j++)
{
if(j==0)
cout<<w->data;
else
cout<<" "<<w->data;
w=w->next;
}
cout<<endl;
//进行删除操作
len=n;
w=head->next;
q=head; //q的后继是w
for(j=0; j<n; j++)
{
if(w->data == k)
{
q->next=w->next; //让前驱指针指向要被删除节点的后继
w->next=NULL; //将该节点孤立
delete(w); //然后删除掉
len--; //长度减1
w=q->next; //w指向q的后继
if(!w) //如果w指向为空,直接跳出,没有你要再循环了
{
break;
}
}
else
{
w=w->next; //正常情况下,w和q指针往后移动,寻找要被删除的数值!
q=q->next;
}
}
cout<<len<<endl;
w=head->next;
for(j=0; j<len; j++)
{
if(j==0)
cout<<w->data;
else
cout<<" "<<w->data;
w=w->next;
}
cout<<endl;
return 0;
}
数据结构之 线性表---单链表操作A (删除链表中的指定元素)
标签:des blog io os sp for 数据 div log
原文地址:http://www.cnblogs.com/yspworld/p/4094025.html